-1

The code below is from Creating a horizontal bar plots in the reverse direction.

I'd like to make a horizontal bar chart in the reverse direction but with a fixed scale. I'd like the scale of the plot to be fixed to 0 to 50 rather than the current 0 to 30.

I've tried changing scale_y_continuous() to scale_y_discret() and I've tried adding ylim() but I can't seem to get it to work.

Thanks!

mtcars
mtcars$`car name` <- rownames(mtcars) 


ggplot (mtcars, aes (x=`car name`, y=-mpg)) +         
  geom_bar (position = position_dodge(), stat = "identity",fill="red",colour="black") + 
  coord_flip () +  theme_classic() +
  scale_x_discrete(name = "", position = "top") +    
  scale_y_continuous(name = "mpg",
                     breaks = seq(0, -30, by = -10),  
                     labels = seq(0,  30, by =  10))  + theme(axis.text.y = element_blank())
LLL
  • 723
  • 1
  • 9
  • 27
  • 2
    just add `limits = c(-50,0)` to the `scale_y_continuous`function? So `scale_y_continuous(name = "mpg",limits = c(-50,0), breaks = seq(0, -50, by = -10), labels = seq(0, 50, by = 10))` or simply run `scale_y_continuous(name = "mpg",limits = c(-50,0))`. In addition use `geom_col()` instead of `geom_bar` – Roman May 22 '18 at 13:02
  • Use `range =c(0, 50)` for y-axis. – SamAct May 22 '18 at 13:04
  • @Jimbou You could define the y-axis before plotting. Like: `y <- list( showgrid=TRUE, title = "Title here", titlefont = f, range=c(0, 50) )`. Then use it under `theme()`. It a long route I get it. But easy if you want to make quick changes later. What do you think? – SamAct May 22 '18 at 13:23
  • @SamAct How you use it under `theme()`? – Roman May 22 '18 at 13:29
  • @Jimbou if i remember correctly its `axis()` command inside `theme()` – SamAct May 22 '18 at 13:41
  • @SamAct which one? Please show the complete code. – Roman May 22 '18 at 13:43

1 Answers1

-1

you can use limits to set a limit on your y scale, It's a numeric vector of length two describing the scale limits.

as @jimbou mentioned in the comments, your code will be something like this:

ggplot (mtcars, aes (x=`car name`, y=-mpg)) +         
  geom_bar (position = position_dodge(), stat = "identity",fill="red",colour="black") + 
  coord_flip () +  theme_classic() +
  scale_x_discrete(name = "", position = "top") +    
  scale_y_continuous(name = "mpg",
                     limits = c(-50,0),
                     breaks = seq(0, -50, by = -10),  
                     labels = seq(0,  50, by =  10))  + theme(axis.text.y = element_blank())

you can also see here

Alaleh
  • 1,008
  • 15
  • 27