ggplot 的翻转轴

Elr*_*ant 0 r ggplot2 ridgeline-plot

我的数据框如下所示:

df <- data.frame(label=c("yahoo","google","yahoo","yahoo","google","google","yahoo","yahoo"), year=c(2000,2001,2000,2001,2003,2003,2003,2003))
Run Code Online (Sandbox Code Playgroud)

如何产生这样的热图:

library(ggplot2)
library(ggridges)
theme_set(theme_ridges())
ggplot(
  lincoln_weather, 
  aes(x = `Mean Temperature [F]`, y = `Month`)
  ) +
  geom_density_ridges_gradient(
    aes(fill = ..x..), scale = 3, size = 0.3
    ) +
  scale_fill_gradientn(
    colours = c("#0D0887FF", "#CC4678FF", "#F0F921FF"),
    name = "Temp. [F]"
    )+
  labs(title = 'Temperatures in Lincoln NE') 
Run Code Online (Sandbox Code Playgroud)

如何翻转绘图轴,即以年份为 x 轴,以 y 轴为标签?

小智 6

好吧,只需使用coord_flip(). 请参阅ggplot2 文档。为了使事情变得整洁,请使用以下方法旋转轴标签axis.text.x并使用以下方法重新排列月份 LTR scale_y_discrete

ggplot(
    lincoln_weather, 
    aes(x = `Mean Temperature [F]`, y = `Month`)
) +
    geom_density_ridges_gradient(
        aes(fill = ..x..), scale = 3, size = 0.3
    ) +
    scale_fill_gradientn(
        colours = c("#0D0887FF", "#CC4678FF", "#F0F921FF"),
        name = "Temp. [F]"
    )+
    labs(title = 'Temperatures in Lincoln NE') +
coord_flip()+
theme(axis.text.x = element_text(angle = 90, hjust=1))+
scale_y_discrete(limits = rev(levels(lincoln_weather$Month)))
Run Code Online (Sandbox Code Playgroud)

现在,这似乎有点不可思议,为什么scale_yscale_x?似乎ggplot首先构造绘图元素,然后才进行翻转、旋转、应用样式等,并且由于月份最初位于 y 轴上,因此您需要使用scale_y_discrete.

如果您的数据现在具有重要的顺序,那么您显然可以跳过整个过程scale_y_discrete

  • 请注意:从去年的 `ggplot2` 3.0.0 开始,符号 `..x..` 并未被弃用,但鼓励将其替换为 `stat(x)`。https://ggplot2.tidyverse.org/news/index.html#new-features-1 (3认同)