首页 > 解决方案 > 第二个传说ggplot

问题描述

我有以下数据框和ggplot:

dat1 <- read.table(text = "row variable value percents
1 Base 0.0029 2.61%
2 Base 0.0022 58.59%
3 Base 0.0056 66.41%
4 Base 0.0106 73.68%
1 ATE 0.00007555184 2.61%
2 ATE 0.00128906474 58.59%
3 ATE 0.00371889655 66.41%
4 ATE 0.00780957462 73.68%", header = TRUE)

ggplot(dat1, aes(x = row, y = value, fill = variable)) + 
  geom_bar(stat = "identity") +
  xlab("\nNtile") +
  ylab("Estimate\n") +
  theme_bw() +
  ggtitle("Base line + ATE by Ntile (as defined by CATE)") +
  labs(fill = "Value", caption = "Note: ATE as % of baseline on grid in black")

理想情况下,我想获得第二个图例,该图例仅将percents列列出到其相关栏。每个百分比都是 ATE,表示为 Base 的百分比。我有一种将它们放在实际图上的方法,但是当某些百分比为负数时看起来很奇怪(我用不同的数据制作了很多这些)。所以像这样的传说:

百分比:

1 - 2.61%

2 - 58.59%

3 - 66.41%

4 - 73.68%

但在实际情节上没有任何点或条。我试图利用这一点geom_pointaes但这会将实际点放在情节上。

编辑:添加示例图例的草图

在此处输入图像描述

标签: rggplot2

解决方案


label您可以放置​​不可见的文本,并为您的图例显示美观的比例。不过,您需要覆盖一些美学。

library(ggplot2)
#> Warning: package 'ggplot2' was built under R version 4.0.3

dat1 <- read.table(text = "row variable value percents
1 Base 0.0029 2.61%
2 Base 0.0022 58.59%
3 Base 0.0056 66.41%
4 Base 0.0106 73.68%
1 ATE 0.00007555184 2.61%
2 ATE 0.00128906474 58.59%
3 ATE 0.00371889655 66.41%
4 ATE 0.00780957462 73.68%", header = TRUE)

ggplot(dat1, aes(x = row, y = value, fill = variable)) + 
  geom_bar(stat = "identity") +
  geom_text(aes(label = percents), alpha = 0) +
  scale_discrete_identity(
    "label", 
    guide = guide_legend(override.aes = list(
      alpha = 1, label = 1:4
    ))) +
  xlab("\nNtile") +
  ylab("Estimate\n") +
  theme_bw() +
  ggtitle("Base line + ATE by Ntile (as defined by CATE)") +
  labs(fill = "Value", caption = "Note: ATE as % of baseline on grid in black")

reprex 包于 2021-02-24 创建(v1.0.0)


推荐阅读