我正在尝试为x轴上的一个类别创建一个具有两个或多个值(条形图)的条形图。但是,它不能与ggplot()-function一起使用。它不会显示相邻的条。我认为价值观是重叠的。但是,我将位置设置为“dodge”。
我有两个数据集,一个是2020年的数据集,另一个是2019年的数据集,具有相同的类别,我想将它们一起绘制在一个条形图中,每个类别有两个条形图。
我使用了以下代码:tgc_combi = rbind(tgc20, tgc19)
#首先,我合并了两个数据集,然后尝试绘制它们:
ggplot(tgc_combi, aes(x=Category, y=Visitors)) +
ggtitle("Number of visitors in each category")+xlab("Category")+ylab("Visitor numbers") +
theme(plot.title = element_text(hjust = 0.5))+
geom_bar(position="dodge", stat="identity") +
geom_errorbar(aes(ymin=Visitors-se, ymax=Visitors+se),
width=.2,
position=position_dodge(.9))
也许是因为类别在tgc20和tgc19中是相同的?有谁能帮帮我吗?
发布于 2020-07-20 03:16:47
您的aes
中缺少group
。如果没有group
,就无法区分2019年和2020年的数据。此外,如果你有较浅的颜色条,你会注意到较低的值有较深的阴影,在您的示例中,这恰好是2020值。我假设你已经计算了se
,并且在你的数据框中有它们。
下面的代码
c <- c("BEHAV", "BIRTH", "CONS", "EDU", "GE", "HEALTH", "NEW", "OUT")
v <- c(83, 27, 16, 19, 106, 15, 4, 12)
se1 <- c(8.8,3.3,0.9,2.1,5.6,1.1,0.5,2.8)
y <- c(rep(2019,8))
tgc19 <- data.frame(Category=c, Visitors=v, Year=y, se=se1)
v2 <- c(53, 13, 3, 4, 39, 7, 3, 11)
se2 <- c(9.8,2.3,1.9,1.5,4.6,0.6,1.1,2.2)
y2 <- c(rep(2020,8))
tgc20 <- data.frame(Category=c, Visitors=v2, Year=y2, se=se2)
tgc_combi <- rbind(tgc20,tgc19)
tgc_combi$Category <- factor(tgc_combi$Category, levels=c)
dodge <- position_dodge(width = 0.9)
limits <- aes(ymax = Visitors + se,
ymin = Visitors - se)
ggplot(tgc_combi, aes(x=Category, y=Visitors, group=Year, fill=Year, color=Year)) +
labs( title="Number of visitors in each category", x = "Category", y= "Visitor numbers") +
geom_bar(stat="identity", position="dodge") +
scale_x_discrete(labels=unique(tgc_combi$Category)) +
theme(plot.title = element_text(hjust = 0.5)) +
geom_errorbar(limits, position = dodge, width = 0.2, color=c("red"))
提供以下输出:
https://stackoverflow.com/questions/62981249
复制相似问题