Sam Pickwick
Sam Pickwick

Reputation: 313

Second legend ggplot

I have the following data frame and 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")

Ideally I would like to get a second legend that just lists the percents column to their associated bar. Each percent is the ATE expressed as a percentage of the Base. I have a method of putting them on the actual plot but it's strange to look at when some percentages are negative (I'm making quite a few of these with different data). So a legend like :

Percents:

1 - 2.61%

2 - 58.59%

3 - 66.41%

4 - 73.68%

But without any point or bars on the actual plot. I tried using geom_point to take advantage of aes but that puts actual points on the plot.

Edit: Adding a sketch of example legend

enter image description here

Upvotes: 0

Views: 52

Answers (2)

teunbrand
teunbrand

Reputation: 37913

You can place invisible text and have a scale for the label aesthetic display the legend for you. You'd need to override some of the aesthetics though.

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

Created on 2021-02-24 by the reprex package (v1.0.0)

Upvotes: 2

Jon Spring
Jon Spring

Reputation: 66415

Maybe this could work?

dat1 %>%
  mutate(x_label = paste(row, percents, sep = "\n")) %>%

ggplot(aes(x = x_label, 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")

enter image description here

Upvotes: 0

Related Questions