r - X 轴和堆叠条中的右框

标签 r ggplot2

在这样的情节

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 值?

最佳答案

要回答这个问题,只需调整所涉及的美学、ysize 即可。

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

另一种选择是首先改变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()

enter image description here

关于r - X 轴和堆叠条中的右框,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60170270/

相关文章:

r - 在 kableExtra 中使用 cell_spec 时,使表中的 NA 值只是空白单元格

R将默认原点设置为as.Date

r - 可以使用 ggplot2 在 R 中创建此图表吗?

r - 如何在 ggplot2 中显示曲线的方向?

R reprex 没有为非常高的图呈现正确的 ggplot 输出

r - 使用 ggplot2 表示散点图中每个点的小饼图

R data.table 根据字符串值将一行拆分为多行

r - 在 R 中组合 tableGrob 和 ggplot 对象时改变填充

r - 如何使 ggplot2 中的图例与我的情节高度相同?

python - R sparklyr 包作为 Spark 的前端有多快?