如何在r中使用ggplot和geom_bar()在柱状图上添加y轴值?

问题描述 投票:0回答:1

你好,我一直想通过特定列的和来总结我的数据集,并直接使用ggplot和geom_bar()来做,而不是使用tidyvers和dplyr库。

我读到了关于权重美学的文章,它可以帮助将条形图绘制成特定特征的总和而不是计数,而且它也成功了。

问题是我无法在条形图上绘制y值,因为我不知道应该如何写geom_text(??)代码。

p1<-ggplot(df, aes(x= ageBracket, fill= movement, **weight= amount**))+ geom_bar(width= 0.5, position= 'dodge')+ theme_hc()+scale_x_discrete('Age Group', limits=c("16 to 25 years", "26 to 35 years", "36 to 45 years", "> 46 years"))+ theme(legend.position= "bottom",legend.background = element_rect(fill="lightblue", size=0.2, linetype="solid"))+ scale_fill_brewer(palette = "Dark2")+ scale_y_continuous("Amount per Age Group",labels = comma)+ **geom_text(?????)**
print(p1)

Blockquote

这里fill帮我隔离了我躲过的条形图,weight帮我根据:movement &ageBracket的过滤器进行数据相加,我只是想把y轴的值放在各自的条形图上面,不想单独建立一个数据框。我应该怎么做?

r ggplot2 data-visualization geom-bar geom-text
1个回答
0
投票

当前版本的ggplot2在使用权重美学时,不允许在geom_text()中使用标签。你得先把数据框总结出来,然后用标签美学的老方法来做。

实际上,并不需要那么多额外的工作,如使用mtcars数据集所示。只需要额外的两行字,如果把结果向前管,就不需要新建一个数据框。

library(ggplot2)
library(dplyr)
data(mtcars)

(1)使用权重美学来求和。mpg 可变 amcyl. 不能给条形图添加标签(6行)。

mtcars %>%
  mutate(am=factor(am, labels=c("auto","manual")), cyl=factor(cyl)) %>%
  ggplot(aes(x=cyl, fill=am, weight=mpg)) + 
  geom_bar(width=0.5, position='dodge') +
  labs(y="Total miles/gallon", x="Cylinders", fill="Transmission") +
  theme_minimal()

(2)先汇总数据,然后用geom_text进行标签美工,可以给条形图添加标签(多2行)。

mtcars %>%
  mutate(am=factor(am, labels=c("auto","manual")), cyl=factor(cyl)) %>%
  group_by(cyl, am) %>%  # extra
  summarise(n = sum(mpg)) %>% # extra
  ggplot(aes(x=cyl, fill=am, y=n, label=n)) + 
  geom_col(width=0.5, position='dodge') +
  geom_text(position=position_dodge(0.5), vjust=-0.25) + 
  labs(y="Total miles/gallon", x="Cylinders", fill="Transmission") +
  theme_minimal()

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.