简体   繁体   English

ggplot2 中的分组反向条 plot

[英]Grouped reversed bar plot in ggplot2

I would like to recreate this plot:我想重新创建这个 plot:

示例_1.png

My data looks like this:我的数据如下所示:

leafnumber <- c(6,7,8,9,6,7,8,9)
PU <- c(30,15,7,0,10,36,7,9)
weeknumber <- c(8,8,8,8,9,9,9,9)

df <- data.frame(leafnumber, PU, weeknumber)

So I want leafnumber to end up on the Y-axis and PU on the X-axis.所以我希望leafnumber最终在Y轴上,PU在X轴上。 And weeknumber can be used to show distribution over time. weeknumber 可用于显示一段时间内的分布。

Here is my first attempt:这是我的第一次尝试:

ggplot(df,aes(leafnumber, PU)) +
  geom_bar(stat = "identity") +
  coord_flip()

I am not sure how to get from a bar plot to a 'grouped' barplot, like the one in the image.我不确定如何从条形图 plot 到“分组”条形图,就像图像中的那个。

The goal is to have this distribution for each weeknumber on the X-axis so I can see the distribution change within time.目标是在 X 轴上为每个周数提供此分布,以便我可以看到分布随时间的变化。

What I do not mean is this:我的意思不是这个:

ggplot(df,aes(leafnumber, PU, fill=weeknumber)) +
  geom_bar(stat = "identity") +
  coord_flip()

Any suggestions/solutions for this problem would be appreciated.对此问题的任何建议/解决方案将不胜感激。

If your actual dataset has a large number of observations for each leaf / PU, you can use the ggridges package to get a similar plot, eg如果您的实际数据集对每个叶子 / PU 有大量观察,您可以使用ggridges package来获得类似的 plot,例如

library(tidyverse)
library(ggridges)

# Make 'larger' fake data
leafnumber <- c(runif(1, 6, n = 100),
                runif(3, 9, n = 100),
                runif(5, 12, n = 100),
                runif(10, 15, n = 100),
                runif(15, 18, n = 100))

PU <- factor(c(rep("1", 100), rep("2", 100),
        rep("3", 100), rep("4", 100), rep("5", 100)),
        levels = c("1", "2", "3", "4", "5"))

weeknumber <- c(8,8,8,8,8,9,9,9,9,9)

df <- data.frame(leafnumber, PU, weeknumber)

# Plot the data
ggplot(df, aes(x = leafnumber, y = PU, height = stat(density))) + 
  geom_density_ridges(stat = "binline", bins = 40,
                      scale = 0.95, draw_baseline = FALSE) +
  coord_flip()

示例_1.png

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM