1

I wanted to create a histogram with legends above these bars. the legends represents the average hours of sleep per day.

ggplot(average_sleep_per_day) +
  geom_col(aes(x = reorder(day, average_sleep), y = average_sleep, fill = average_sleep))  +
            labs(title = "average_sleep_per_day") +
            theme_classic() +
            theme(panel.background = element_blank(),
                   plot.title = element_text(hjust = 0.5, size=10, face = "bold")) +
            geom_text(aes(label = round(average_sleep, 1)),
            position = position_stack(vjust = 1.02))

My data:

average_sleep_per_day <- structure(
  list(
    day = c("Dimanche", "Jeudi", "Lundi"),
    average_sleep = c(7.54575757575758, 6.68828125, 6.99166666666667)
  ),
  row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame")
)
stefan
  • 90,330
  • 6
  • 25
  • 51
  • 4
    You specified `x` and `y` as local aesthetics in `geom_col`. Either make them global by moving them to ` ggplot()` or add them to aes() in geom_text too. – stefan Jan 24 '23 at 12:13
  • I tried and had this result "`geom_text()` requires the following missing aesthetics: label" – Fokou Serges Jan 25 '23 at 08:18
  • Sounds as if you removed `label=...` from `aes()` in geom_text. If you need more help please provide [a minimal reproducible example](https://stackoverflow.com/questions/5963269/how-to-make-a-great-r-reproducible-example) including a snippet of your data or some fake data. – stefan Jan 25 '23 at 08:26
  • structure( list( day = c("Dimanche", "Jeudi", "Lundi"), average_sleep = c(7.54575757575758, 6.68828125, 6.99166666666667) ), row.names = c(NA,-3L), class = c("tbl_df", "tbl", "data.frame") ) – Fokou Serges Jan 25 '23 at 12:25

1 Answers1

0

As I mentioned in my comment the issue is that specified x and y as local aesthetics in geom_col. To fix that make them global by moving them to ggplot() as I do in the code below or add them to aes() in geom_text too.

average_sleep_per_day <- structure(list(day = c("Dimanche", "Jeudi", "Lundi"), average_sleep = c(7.54575757575758, 6.68828125, 6.99166666666667)), row.names = c(NA, -3L), class = c("tbl_df", "tbl", "data.frame"))

library(ggplot2)

ggplot(average_sleep_per_day, aes(x = reorder(day, average_sleep), y = average_sleep)) +
  geom_col(aes(fill = average_sleep)) +
  labs(title = "average_sleep_per_day") +
  theme_classic() +
  theme(
    panel.background = element_blank(),
    plot.title = element_text(hjust = 0.5, size = 10, face = "bold")
  ) +
  geom_text(aes(label = round(average_sleep, 1)),
    position = position_stack(vjust = 1.02)
  )

stefan
  • 90,330
  • 6
  • 25
  • 51