绘制具有不同比例的多个列

时间:2017-06-24 19:31:47

标签: r plot ggplot2 multiple-axes

我有以下格式的数据:

Section Env.    Ar.     Width   Length
    A   8.38    8.76    7      36
    B   11.84   13.51   11     57
    C   16.69   16.49   17     87
    D   11.04   11.62   9      44
    E   19.56   16.79   20     106
    F   17.93   21.34   19     98

我需要在X轴上设置section,在一个Y轴上设置Env.Ar.,在另一个Y轴设置WidthLength ,因为它有不同的规模。我知道如何使用ggplot在一个Y轴上绘制它们,但我仍然坚持如我所提到的那样用两个不同的Y轴。任何帮助将不胜感激。

谢谢!

1 个答案:

答案 0 :(得分:1)

关于使用这个怎么样?

library(tidyverse)
d <- structure(list(Section = structure(1:6, .Label = c("A", "B", 
                 "C", "D", "E", "F"), class = "factor"), Env. = c(8.38, 11.84, 
                  16.69, 11.04, 19.56, 17.93), Ar. = c(8.76, 13.51, 16.49, 11.62, 
                  16.79, 21.34), Width = c(7L, 11L, 17L, 9L, 20L, 19L), Length = c(36L, 
                  57L, 87L, 44L, 106L, 98L)), .Names = c("Section", "Env.", "Ar.", 
                  "Width", "Length"), class = "data.frame", row.names = c(NA, -6L))
d %>% 
  gather(key, value,-Section) %>% 
  ggplot(aes(Section, value, colour=key, group= key)) + 
  geom_line(size=1.1) + geom_point(size=4)+
  scale_y_continuous(name="Env_Ar",
    sec.axis = sec_axis(~., name = "Width_Length"))

enter image description here

您还可以尝试使用"free_y"缩放的不同方面。这是IMO更清洁和优雅。

d %>% 
  gather(key, value,-Section) %>% 
  mutate(group=ifelse(key %in% c("Width","Length"), 2, 1)) %>% 
  ggplot(aes(Section, value, colour=key, group= key)) + 
  geom_line(size=1.1) + geom_point(size=4)+
  facet_wrap(~group, scales = "free_y")

enter image description here

修改

这里是右y轴的不同缩放(高10倍)的方法

d %>% 
  mutate(Width=Width*10,
         Length=Length*10) %>% 
  gather(key, value,-Section) %>% 
  ggplot(aes(Section, value, colour=key, group= key)) + 
  geom_line(size=1.1) + geom_point(size=4)+
  scale_y_continuous(name="Env_Ar",
                     sec.axis = sec_axis(~.*10, name = "Width_Length"))