ggplot翻转坐标轴

6

我的数据帧看起来是这样的:

df <- data.frame(label=c("yahoo","google","yahoo","yahoo","google","google","yahoo","yahoo"), year=c(2000,2001,2000,2001,2003,2003,2003,2003))

如何制作像这样的热图:
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') 

我如何翻转图表坐标轴,即将年份作为x轴,标签作为y轴?


1
aes()中的值更改为与数据框匹配:ggplot( df, aes(x = year, y = label) ) ... - kabr
1个回答

15

很简单,只需使用coord_flip()。请参见ggplot2文档。为了使事情更整洁,使用axis.text.x旋转轴标签,并使用scale_y_discrete按LTR重新排序月份:

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

现在这似乎有点奇怪,为什么要使用scale_y而不是scale_x?看起来ggplot首先构建图形元素,然后翻转、旋转、应用样式等等。因为月份最初位于y轴上,所以需要使用scale_y_discrete

如果您的数据没有重要的顺序,则可以显然跳过整个scale_y_discrete步骤。


3
注意:自去年 ggplot2 版本 3.0.0 起,符号 ..x.. 并未被弃用,但建议使用 stat(x) 进行替换。https://ggplot2.tidyverse.org/news/index.html#new-features-1 - camille
1
同意,但这是他/她自己的代码。我只是做了一些添加。..x.. 不是我的风格。 - Spätzle

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接