1

I would like to see the y-axis (in the plot is flipped) starting at some arbitrary value, like 7.5

enter image description here

After a little bit of researching, I came across ylim, but in this case is giving me some errors:

Scale for 'y' is already present. Adding another scale for 'y', which will
replace the existing scale.
Warning message:
Removed 10 rows containing missing values (geom_col). 

This is my code, and a way to download the data I'm using:

install.packages("remotes")
remotes::install_github("tweed1e/werfriends")

library(werfriends)

friends_raw <- werfriends::friends_episodes

library(tidytext)
library(tidyverse)


#"best" writers with at least 10 episodes
friends_raw %>%
  unnest(writers) %>%
  group_by(writers) %>%
  summarize(mean_rating = mean(rating),
            n = n()) %>%
  arrange(desc(mean_rating)) %>%
  filter(n > 10) %>%
  head(10) %>%
  mutate(writers = fct_reorder(writers, mean_rating)) %>%
  ggplot(aes(x = writers, y = mean_rating, fill = writers)) + geom_col() + 
  coord_flip() + theme(legend.position = "None") + scale_y_continuous(breaks = seq(7.5,10,0.5)) + 
  ylim(7.5,10)
dc37
  • 15,840
  • 4
  • 15
  • 32
Norhther
  • 545
  • 3
  • 15
  • 35

2 Answers2

4

You should use coord_cartesian for zoom in a particular location (here the official documentation: https://ggplot2.tidyverse.org/reference/coord_cartesian.html).

With your example, your code should be something like that:

friends_raw %>%
  unnest(writers) %>%
  group_by(writers) %>%
  summarize(mean_rating = mean(rating),
            n = n()) %>%
  arrange(desc(mean_rating)) %>%
  filter(n > 10) %>%
  head(10) %>%
  mutate(writers = fct_reorder(writers, mean_rating)) %>%
  ggplot(aes(x = writers, y = mean_rating, fill = writers)) + geom_col() + 
  coord_flip() + theme(legend.position = "None") + scale_y_continuous(breaks = seq(7.5,10,0.5)) + 
  coord_cartesian(ylim = c(7.5,10))

If this is not working please provide a reproducible example of your dataset (see: How to make a great R reproducible example)

dc37
  • 15,840
  • 4
  • 15
  • 32
1

I found out the solution. With my actual plot, the answer submitted by @dc37 didn't work because coord_flip() and coord_cartesian() exclude each other. So the way to do this is:

friends_raw %>%
  unnest(writers) %>%
  group_by(writers) %>%
  summarize(mean_rating = mean(rating),
            n = n()) %>%
  arrange(mean_rating) %>%
  filter(n > 10) %>%
  head(10) %>%
  mutate(writers = fct_reorder(writers, mean_rating)) %>%
  ggplot(aes(x = writers, y = mean_rating, fill = writers)) + geom_col() + 
  theme(legend.position = "None") + 
  coord_flip(ylim = c(8,8.8))
Norhther
  • 545
  • 3
  • 15
  • 35