ggplot的翻转轴

时间:2019-03-18 13:22:15

标签: r ggplot2

具有这样的数据结构:

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 个答案:

答案 0 :(得分:1)

好吧,只需使用coord_flip()。请参阅ggplot2 documentation。为了使内容整洁,请使用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首先构造了plot元素,然后才进行翻转,旋转,应用样式等等,并且由于月份最初位于y轴上,因此您需要使用scale_y_discrete

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