R语言作图系列2——双坐标轴

1. 问题

对于我们这专业时常要做个降雨量和温度的双坐标轴图,

2. 数据格式

注意月份的大小(levels)水平,会影响图像顺序排列这里设置6-5跨年的排列。

> str(temperature1)
'data.frame':	12 obs. of  3 variables:
 $ 月份  : Factor w/ 12 levels "6","7","8","9",..: 1 2 3 4 5 6 7 8 9 10 ...
 $ 降雨量: num  133.1 75.6 3 22.6 36.2 ...
 $ 月平均: num  25.9 28.4 30 25.5 19.7 13.6 8 5.6 9.5 13.5 ...
> head(temperature1)
  月份 降雨量 月平均
1    6  133.1   25.9
2    7   75.6   28.4
3    8    3.0   30.0
4    9   22.6   25.5
5   10   36.2   19.7
6   11   63.9   13.6

3. 代码

数据导入整理的省略,详细看R语言科研绘图系列1——数据整理篇

library(ggplot2)
temperaturecolor <- "red"##温度颜色
precipitationcolor <- rgb(0.2,0.6,0.9,1)##降雨量颜色
ggplot(temperature1,aes(x=temperature1$月份,y=temperature1$月平均))+
  geom_bar(aes(y=temperature1$降雨量/10),stat="identity",size=0.5,fill=precipitationcolor,color="black")+
  geom_point(aes(y=temperature1$月平均),shape=15,size=4,color=temperaturecolor)+geom_line(aes(group=1),size=1,color=temperaturecolor)+
  scale_y_continuous(
    name = "温度 Temperature(℃)",
    sec.axis=sec_axis(~.*10,name = "降雨量 precipitation(mm)")
      )+
  scale_x_discrete(name = "月份 month")+
  mytheme

注意细节:
1.aes(x=temperature1 月 份 , y = t e m p e r a t u r e 1 月份,y=temperature1 ,y=temperature1月平均);
2.aes(y=temperature1$降雨量/10);
3.其实折线和柱子都用的左边的y轴坐标

4. 引用

Dual Y axis with R and ggplot2

5. 图片

在这里插入图片描述
关键问题:本人审美急需提高,欢迎评论。

猜你喜欢

转载自blog.csdn.net/LeaningR/article/details/110849777