【问题标题】:ggplot bar plot side by side using two variables [duplicate]使用两个变量并排的ggplot条形图[重复]
【发布时间】:2017-08-06 20:04:21
【问题描述】:

我想在 R Studio 中使用 ggplot 并排使用两个变量来创建条形图。我尝试遵循我在网上找到的其他人的建议,但我无法让它发挥作用。

这是我正在使用的数据:

x <- c(5,17,31,9,17,10,30,28,16,29,14,34)

y <- c(1,2,3,4,5,6,7,8,9,10,11,12)

day <- c(1,2,3,4,5,6,7,8,9,10,11,12)

所以,我想要做的是在 x 轴上设置天数,并在 x 和 y (x 和 y 被着色)对应的天数上并排显示条形图。

我做的第一件事是制作一个数据框:

df1 <- data.frame(x,y,day)

然后我尝试了:

ggplot(df1, aes(x = day, y = x,y)) + geom_bar(stat = "identity",color = x, width = 1, position="dodge")

但我就是无法让它正常工作。关于如何实现这一目标的任何建议?

【问题讨论】:

  • 后续问题:您是否希望颜色基于当天?还是颜色取决于它们是在“x”还是“y”组中?

标签: r


【解决方案1】:

你的想法是对的,我认为 reshape2 包中的 melt() 函数就是你要找的。​​p>

library(ggplot2)
library(reshape2)

x <- c(5,17,31,9,17,10,30,28,16,29,14,34)
y <- c(1,2,3,4,5,6,7,8,9,10,11,12)
day <- c(1,2,3,4,5,6,7,8,9,10,11,12)


df1 <- data.frame(x, y, day)
df2 <- melt(df1, id.vars='day')
head(df2)

ggplot(df2, aes(x=day, y=value, fill=variable)) +
    geom_bar(stat='identity', position='dodge')

编辑 我认为 tidyverse tidyr 包中的 pivot_longer() 函数现在可能是处理这些类型的数据操作的更好方法。它提供了比melt() 更多的控制权,并且还有一个pivot_wider() 函数可以做相反的事情。

library(ggplot2)
library(tidyr)

x <- c(5,17,31,9,17,10,30,28,16,29,14,34)
y <- c(1,2,3,4,5,6,7,8,9,10,11,12)
day <- c(1,2,3,4,5,6,7,8,9,10,11,12)


df1 <- data.frame(x, y, day)
df2 <- tidyr::pivot_longer(df1, cols=c('x', 'y'), names_to='variable', 
values_to="value")
head(df2)

ggplot(df2, aes(x=day, y=value, fill=variable)) +
    geom_bar(stat='identity', position='dodge')

【讨论】:

  • 完美,正是我想要的……感谢您的帮助
【解决方案2】:

或者您可以使用facet_wrap 生成两个图:

  library("ggplot2")
  library("reshape")
  x <- c(5,17,31,9,17,10,30,28,16,29,14,34)
  y <- c(1,2,3,4,5,6,7,8,9,10,11,12)
  day <- c(1,2,3,4,5,6,7,8,9,10,11,12)
  df1 <- data.frame(x,y,day)
  df2 <- reshape::melt(df1, id = c("day"))
  ggplot(data = df2, aes(x = day, y = value, fill = variable)) + geom_bar(stat = "identity")+ facet_wrap(~ variable) + scale_x_continuous(breaks=seq(1,12,2))

如果您想要根据当天颜色的条形使用fill = day

ggplot(data = df2, aes(x = day, y = value, fill = day)) + geom_bar(stat = "identity") + facet_wrap(~ variable) + scale_x_continuous(breaks=seq(1,12,2)) 

【讨论】:

  • 另外值得注意的是,如果您将day 转换为因子,那么日子将不会像这样连续不断
  • 您可以使用 + scale_x_continuous(breaks=seq(1,12,2)) 表示 x 轴上的整数值。
猜你喜欢
  • 2017-06-24
  • 2021-12-15
  • 1970-01-01
  • 2013-02-15
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多