-1

i use geom_bar in ggplot to visualize the purchase decision of customers (3 factor levels purchase, may be, no purchase. The decisions are grouped for several product groups with facet_wrap.

ggplot(df, aes(x= status_purchase)) + 
  geom_bar() + 
  theme(axis.text.x = element_text(angle = 90)) + 
  facet_wrap(~ product_group)

Not surprisingly this works fine. Do i have any options to visualize another variable for the groups in facet_wrap (e.g. total expenses for each product group)? A kind of bubble in the respective size placed in the right upper corner of the plot or at least the sum of the expenses in the headline would be nice.

Thank you for your answers.

Philipp

Philipp Schulz
  • 131
  • 1
  • 8
  • You can add any text to legends/title using paste. Or add arbitrary text to the plot using `geom_text`. – dario Oct 05 '21 at 14:34
  • Quick answer to your question is "yes!", but a more specific answer will depend on what you want to add. Best option is probably to have a separate dataset that is used to plot labels (if you're looking to put text in each facet), since it looks like you're wanting some summary data shown, right? Can you specify a bit more what you would want specifically and provide an example of what you want to show? – chemdork123 Oct 05 '21 at 21:06

1 Answers1

0

OP. In the absence of a specific example, let me demonstrate one way to do this that uses geom_text() to display summary data for a given dataset that is separated in to facets.

In this example, I'll use the txhousing dataset (which is part of ggplot2):

library(dplyr)
library(tidyr)
library(ggplot2)

df <- txhousing
df %>% ggplot(aes(x=month, y=sales)) + geom_col() +
  facet_wrap(~year)

enter image description here

Let's say we wanted to display a red total of sales for a year in the upper right portion of each facet. The easiest way to do this is to first calculate our summary data in a separate dataset, then overlay that information according to the facets via geom_text().

df_summary <- df %>%
  group_by(year) %>%
  summarize(total = sum(sales, na.rm = TRUE))

df %>% ggplot(aes(x=month, y=sales)) + geom_col() +
  facet_wrap(~year) +
  geom_text(
    data=df_summary, x=12, y=33000, aes(label=total),
    hjust=1, color='red', size=3
  )

enter image description here

I override the mapping for the x and y aesthetics in the geom_text() call. As long as the df_summary dataset contains a column called year, the data will be placed on the facets properly.

I hope you can apply a similar idea to your particular question.

chemdork123
  • 12,369
  • 2
  • 16
  • 32