带有两个Y轴的ggplot [英] ggplot with two Y axes

查看:82
本文介绍了带有两个Y轴的ggplot的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

dataframe:-  df

  Period        v1      v2
1   2002        1       1
2   2003        5       12
3   2004        9       28
4   2005        16      66
5   2006        23      115

Code:-

ggplot() + geom_line(data=df, aes(x=Period, y=v1, group=1, color="v1")) + 
geom_line(data=df, aes(x=Period, y=v2, group=1, color="v2"))+ theme(legend.title=element_blank()) + scale_y_continuous(name="Count") +
geom_point(data=df, aes(x=Period, y=v1, group=1)) + geom_point(data=df, aes(x=Period, y=v2, group=1))

我正在绘制带有点的两个折线图.我遇到的问题是,值以不同的幅度增加,因此其中一个折线图"v1" 在以下位置压缩:规模,因此更难阅读.任何人都可以在解决这个问题上提出建议吗?还可以缩短此代码吗?

I am plotting two line graph along with points.The issue I am experiencing is that the values increase in different magnitude and so one of the line graphs "v1" gets condensed at the lower end of the scale and thus harder to read. can anyone please advice in solving this? Also can this code be shortened?

推荐答案

使用ggplot2的想法是将数据转换为所谓的长格式,其中每个观察值占用一行:

The idea with ggplot2 is that you convert your data into so-called long format, where each observation occupies one line:

library(tidyr)
plot_data <- gather(df, key, value, -Period)
head(plot_data)
##   Period key value
## 1   2002  v1     1
## 2   2003  v1     5
## 3   2004  v1     9
## 4   2005  v1    16
## 5   2006  v1    23
## 6   2002  v2     1

现在,您可以将变量value映射到y,将key映射到颜色以更容易地绘制相同的图:

Now, you can map the variable value to y and key to colour to get the same plot easier:

ggplot() + geom_line(data=plot_data, aes(x=Period, y=value, colour = key)) + 
  theme(legend.title=element_blank()) + 
  geom_point(data=plot_data, aes(x=Period, y=value)) +
  scale_y_continuous(name="Count")

我不确定数据越来越难读取,这到底是什么意思.也许您想要对数的y轴?

I'm not sure what exactly you mean by the data getting harder to read. Maybe, you want a logarithmic y-axis?

ggplot() + geom_line(data=plot_data, aes(x=Period, y=value, colour = key)) + 
  theme(legend.title=element_blank()) +
  geom_point(data=plot_data, aes(x=Period, y=value)) +
  scale_y_log10(name="Count")

这篇关于带有两个Y轴的ggplot的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆