ggplot 的翻转轴
Flipping Axes of ggplot
我的数据框如下所示:
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 轴?
好吧,简单地使用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
首先构造绘图元素,然后才进行翻转、旋转、应用样式等操作,并且由于月份最初位于 y 轴上,因此您需要使用 scale_y_discrete
.
如果您的数据现在有重要的顺序,那么您显然可以跳过整个 scale_y_discrete
事情。
我的数据框如下所示:
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 轴?
好吧,简单地使用coord_flip()
。参见 ggplot2
documentation。为了使事情变得整洁,使用 axis.text.x
旋转轴标签并使用 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
事情。