【问题标题】:ggplot - how can I show percentage proportions and total sumggplot - 我如何显示百分比和总和
【发布时间】:2019-11-05 08:21:33
【问题描述】:

我的代码:

  ggplot(data=data,aes(x=month,y=as.numeric(properties),fill=show)) + 
  theme_light() + 
  geom_col(alpha=.8) +
        geom_text(aes(label=round(..y../1000,1),group = c(show)),
        position=position_stack(vjust=.5),vjust=-.2,size=2) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1,size=6),
              legend.position = "bottom",
              axis.title = element_text(size = 8),
              axis.title.y.left = element_text(size = 10)) +
  ylab("Properties") + xlab("Month") +
  scale_fill_manual("Show", values = c("YES" = '#b3b3b3', "NO" = '#8080ff'))

我的情节:

示例数据:

month   show properties
-------------------
2017-05 NO  2.1     
2017-05 YES 4.1     
2017-06 NO  2.1     
2017-06 YES 4.2
...

如何将每组的总和更改为百分比比例,以及如何同时在每个条形上添加总单位总和?

【问题讨论】:

  • 请包含一些数据,例如使用dput(data)
  • 我刚刚在描述中添加了示例数据
  • 列中似乎缺少“属性”?
  • @brtk 在表格中显示示例数据并不理想,因为我们无法将其轻松粘贴到 IDE 中,并且它缺少类型信息。请按照建议使用dput(data)。如果数据太多(或机密),请使用 ``` head(data) %>% dput()```。
  • 我更正了属性

标签: r ggplot2 plot visualization


【解决方案1】:

你快到了。因此对于百分比,您需要添加另一列计算百分比并将其用作 geom_text() 中的标签。对于总和,需要单独计算,并作为geom_text()引入,带有单独的数据框:

# convert to numeric at the start
data <- data %>% mutate(properties=as.numeric(properties))
# calculate percentage
data <- data %>% group_by(month) %>% mutate(perc=round(100*properties/sum(properties),1))
# make another data frame with sum
sumdata <- data %>% group_by(month) %>% summarize(properties=sum(properties))

# almost the same plot with 
g = ggplot(data=data,aes(x=month,y=properties,fill=show)) + 
  theme_light() + 
  geom_col(alpha=.8) +
        geom_text(aes(label=perc,group = c(show)),
        position=position_stack(vjust=.5),vjust=-.2,size=2) +
  theme(axis.text.x = element_text(angle = 45, hjust = 1, vjust = 1,size=6),
              legend.position = "bottom",
              axis.title = element_text(size = 8),
              axis.title.y.left = element_text(size = 10)) +
  ylab("Properties") + xlab("Month") +
  scale_fill_manual("Show", values = c("YES" = '#b3b3b3', "NO" = '#8080ff'))+
 geom_text(data=sumdata,aes(x=month,y=properties+0.15,label=properties),
inherit.aes=FALSE,size=2)

【讨论】:

    猜你喜欢
    • 2022-01-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-04-02
    • 1970-01-01
    • 2021-01-08
    • 2018-11-25
    相关资源
    最近更新 更多