首页 > 解决方案 > 堆叠条中的 X 轴和右框

问题描述

在这样的情节中

library(ggplot2)
df <- data.frame(class = c("a","b","a","b"), date = c(2009,2009,2010,2010), volume=c(1,1,2,0))
df <- df %>% group_by(date) %>% mutate(volumep = 100 * volume/sum(volume))
ggplot(df, aes(x = date, y = volumep, fill = class, label = volumep)) +
    geom_bar(stat = "identity") +
    geom_text(size = 3, position = position_stack(vjust = 0.5)) + coord_flip()

如何增加右侧(类)框中的文本以及如何使 x 轴具有 0、25、50 和 100 值?

标签: rggplot2

解决方案


要回答这个问题,只需调整所涉及的美学,y并且size

ggplot(df, aes(x = date, y = 100*volume, fill = class, label = volume)) +
  geom_bar(stat = "identity") +
  geom_text(size = c(3, 3, 5, 5), position = position_stack(vjust = 0.5)) +
  coord_flip() +
  ylab("volume")

另一个选项是firstmutate的值。volume在这种情况下,无需手动设置 y 轴标签。
问题的编辑后,代码现在如下。

library(ggplot2)
library(dplyr)

df %>%
  group_by(date) %>%
  mutate(volume = 100*volume/sum(volume)) %>%
  ggplot(aes(x = date, y = volume, fill = class, label = volume)) +
  geom_bar(stat = "identity") +
  geom_text(size = c(3, 3, 5, 5), position = position_stack(vjust = 0.5)) +
  coord_flip()

在此处输入图像描述


推荐阅读