【问题标题】:scale on bar plot in reverse direction - ggplot2反向缩放条形图 - ggplot2
【发布时间】:2018-05-22 12:55:13
【问题描述】:

下面的代码来自Creating a horizontal bar plots in the reverse direction

我想制作一个反向的水平条形图,但具有固定比例。我希望将绘图的比例固定为 0 到 50 而不是当前的 0 到 30。

我尝试将scale_y_continuous() 更改为scale_y_discret(),并尝试添加ylim(),但似乎无法正常工作。

谢谢!

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())

【问题讨论】:

  • 只需将limits = c(-50,0) 添加到scale_y_continuous 函数中?所以scale_y_continuous(name = "mpg",limits = c(-50,0), breaks = seq(0, -50, by = -10), labels = seq(0, 50, by = 10)) 或者干脆运行scale_y_continuous(name = "mpg",limits = c(-50,0))。另外使用geom_col() 而不是geom_bar
  • 在 y 轴上使用 range =c(0, 50)
  • @Jimbou 您可以在绘图之前定义 y 轴。喜欢:y &lt;- list( showgrid=TRUE, title = "Title here", titlefont = f, range=c(0, 50) )。然后在theme() 下使用它。这是一条很长的路,我明白了。但是,如果您想稍后进行快速更改,这很容易。你怎么看?
  • @SamAct 在theme()下你是怎么用的?
  • @Jimbou 如果我没记错的话axis()theme() 中的命令

标签: r ggplot2


【解决方案1】:

您可以使用limits 为您的 y 刻度设置一个限制,它是一个长度为 2 的数字向量,用于描述刻度限制。

正如 @jimbou 在 cmets 中提到的,您的代码将是这样的:

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())

你也可以看到here

【讨论】:

    猜你喜欢
    • 2021-02-26
    • 1970-01-01
    • 2011-08-21
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-10-25
    相关资源
    最近更新 更多