2

我的数据框如下所示:

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 轴为标签?

4

1 回答 1

8

好吧,只需使用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)))

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

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

于 2019-03-18T14:23:31.363 回答