函数的Barchart旁边在R

函数的Barchart旁边在R

本文介绍了在带有ggplot()函数的Barchart旁边在R-studio中不起作用的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试为x轴上的类别创建一个具有两个或多个值(条)的条形图.但是,它不适用于ggplot()函数.它没有显示彼此相邻的条形图.我认为价值观重叠了.但是,我将位置设置为"dodge".

I'm trying to create a barchart with two or multiple values (bars) for a category on the x-axis. However, it is not working with the ggplot()-function. It does not show the bars beside one another. I think the values overlay. However, I put the position ="dodge".

我有两个数据集,一个数据集用于2020年,一个数据集用于2019年,具有相同的类别,我想将它们一起绘制在一个条形图中,每个类别有两个条形.

I have two datasets, one for the year 2020, and one for the year 2019, with the same categories and I'd like to plot them together in one barchart with two bars for each category.

我使用了以下代码: tgc_combi = rbind(tgc20,tgc19)#首先,我合并了两个数据集,然后尝试绘制它们:

I used this code:tgc_combi = rbind(tgc20, tgc19) #First, I combined the two datasets, then I tried to plot them:

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中被称为相同吗?谁能帮我吗?

Maybe it is because the categories are called the same in tgc20 and in tgc19?Can anyone please help me?

推荐答案

您在 aes 中缺少 group .如果没有 group ,则无法区分2019年和2020年的数据.此外,如果色条较浅,则较低值的阴影会变暗,而恰恰是2020年值的阴影例子.我假设您已经计算出 se ,并将其保存在数据框中.

You are missing group in your aes. Without group there is no way to distinguish the data from 2019 and 2020. Also, if you had lighter color bars you would have noticed darker shade for the lower values, which happens to be for 2020 values in your example.I am assuming that you have calculated se, and have them in your dataframe.

以下代码

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"))

给出以下输出:

这篇关于在带有ggplot()函数的Barchart旁边在R-studio中不起作用的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-05 20:36