首页 文章

如何连接条形图,就像geom_density_ridges一样用于直方图

提问于
浏览
1

我在R中创建绘图很麻烦 . 如果我有像这样的数据

enter image description here

我想创建:

enter image description here

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)

2 回答

  • 1

    仅供参考,更好地发布您的数据而不是放在屏幕截图中,您还应该发布到目前为止您尝试过的代码 .

    您正在寻找的是 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
    
  • 2

    你的刻面情节是在正确的轨道上 . 就像我在评论中所说,你试图显示 Value 分布,而不是 Value 手段 . 您可以手动设置中断并计算要在 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 .

相关问题