这个问题在这里已经有了答案:
How to create side-by-side bar charts (for multiple series) with ggplot?
(1 个回答)
4年前关闭。
我想在 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")
但我就是无法让它正常工作。关于我如何实现这一目标的任何建议?
最佳答案
你的想法是对的,我认为 melt()
来自 reshape2
的函数包就是你要找的。
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')
编辑
我认为
pivot_longer()
来自 tidyverse 的函数 tidyr
包现在可能是处理这些类型数据操作的更好方法。它比 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')
关于r - 使用两个变量并排的ggplot条形图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/42820677/