1

Here is the data set:

d <- tribble(
  ~priceseg,   ~price_n, ~zet_n, ~zet_n2,
     "(0,1]",     16,      2,      24,      
     "(1,3]",     33,      3,      38,
     "(3,5]",     33,      2,      25,
     "(5,6]",     17,      1,      13,
)

And here is the visualisation thanks to @d.b

ggplot(d) +
  geom_col(aes(x = priceseg, y = price_n), fill = ("#F1948A"), colour="black", size = 0.6) +
  geom_line(data = d, mapping = aes(x = priceseg, y = zet_n2, group = 1), colour = "#154360", size = 1) +
  geom_label(data = d, mapping = aes(x = priceseg, y = price_n, label = price_n), nudge_y = -0.6)

Now, I want to add the legend for bar plot and line in the visualisation something like this: Combined line & bar geoms: How to generate proper legend?

Also, I would like to add % in geom_label.

But somehow, I could not manage to implement it. Any help?

datazang
  • 989
  • 1
  • 7
  • 20

1 Answers1

1

Here is an option

# Calculate percentage and add as column to `d`
d <- transform(d, perc = sprintf("%2.1f%%", price_n / sum(price_n) * 100))

# Plot
ggplot(d, aes(x = priceseg)) +
  geom_col(aes(y = price_n, fill = "bar_data"), colour = "black", size = 0.6) +
  geom_line(aes(y = zet_n2, group = 1, colour = "line_data"), size = 1) +
  scale_fill_manual("", values = "#F1948A") +
  scale_colour_manual("", values = "#154360") +
  geom_label(aes(y = price_n, label = perc), nudge_y = -0.6) +
  theme(
      legend.key = element_blank(),
      legend.title = element_blank(),
      legend.box = "horizontal")

You can adjust the fill and colour "labels" by changing the strings "bar_data" and "line_data".

enter image description here

Maurits Evers
  • 49,617
  • 4
  • 47
  • 68