如何连接条形图,就像 geom_density_ridges 对直方图所做的那样

How to connect bar plot, just like geom_density_ridges does for histogram

我在用 R 创建绘图时遇到了麻烦。如果我有像

这样的数据

我要创建:

x 轴为 Sepal.length、Sepal.Width、Petal.Width、Petal.Length ,y 轴是不同的物种,高度是值。并且还根据 y 轴用不同的颜色填充每个条形图。

谢谢!

到目前为止,我已经尝试过:

iris_mean <- aggregate(iris[,1:4], by=list(Species=iris$Species), FUN=mean) 
library(reshape2)
df_mean <- melt(iris_mean, id.vars=c("Species"), variable.name = "Samples", 
  value.name="Values")

ggplot(df_mean,aes(Samples,Values))+
geom_bar(aes(fill=Species),stat="identity")+
  facet_grid(Species~.,scale='free',space='free')+theme(panel.margin = unit(0.1, "lines"))


ggplot(df_mean,aes(x=Samples,y=Species,height =Values))+
  geom_density_ridges2(aes(fill=Species),stat='identity',
                       scale=1.5,
                       alpha=0.1,
                       lty = 1.1)

仅供参考,post 你的数据比放在屏幕截图中更好,你还应该 post 你到目前为止尝试过的代码。

您要找的是facet_grid:

library(tidyverse)

iris_summarized <- iris %>%
 group_by(Species, Sepal.Length) %>%
 summarize(total = n())

ggplot(iris_summarized, aes(x = Sepal.Length, y = total, fill = Species)) + # the fill argument sets the color for the bars
 geom_col() + # use geom_col instead of geom_bar if you are explicitly referencing counts in your data set
 facet_grid(Species ~ ., switch = "y") + # the switch = "y" argument moves the species name to the left side of the graph
 theme(strip.placement = "outside", # this moves the title of each facet to the left of the axis
       strip.background = element_blank()) # this makes the title of each facet not have a background

你的多面情节是在正确的轨道上。就像我在评论中所说的那样,您正在尝试显示值的分布,而不是值的方式。您可以手动设置中断并计算计数以显示在 geom_bar 中,但这很容易变得非常复杂,尤其是因为不同类型的度量具有不同的比例。我建议只坚持使用简单的直方图。我使用 gather 而不是 melt 来制作长数据——这只是偏好。

除了你所拥有的,这是 1. 使用发行版,以及 2. 巧妙地处理主题的问题。如果您移动小平面标签,旋转左侧条带,取出条带背景,并移除面板之间的垂直间距,您基本上得到了一个脊图。我对 ggridges 不是很熟悉,但我猜它会做类似的事情。从这里,您可以调整您认为合适的方式。

library(tidyverse)

iris_long <- as_tibble(iris) %>%
  gather(key = measure, value = value, -Species)

ggplot(iris_long, aes(x = value, fill = Species)) +
  # geom_density_ridges() +
  geom_histogram(show.legend = F) +
  scale_y_continuous(breaks = NULL) +
  labs(x = "Measure", y = "Species") +
  facet_grid(Species ~ measure, scales = "free", switch = "both") +
  theme(strip.background = element_blank(), strip.text.y = element_text(angle = 180), 
        strip.placement = "outside", panel.spacing.y = unit(0, "cm"))
#> `stat_bin()` using `bins = 30`. Pick better value with `binwidth`.

reprex package (v0.2.0) 创建于 2018-07-19。