【问题标题】:Plot multiple columns with different scales绘制具有不同比例的多列
【发布时间】:2017-06-24 19:31:46
【问题描述】:

我有一些数据格式如下:

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 轴上。任何帮助将不胜感激。

谢谢!

【问题讨论】:

标签: r plot ggplot2 multiple-axes


【解决方案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"))

您也可以尝试使用 "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")

编辑

这是一种用于右 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"))

【讨论】:

  • 感谢您的帮助。但是,第一次接近的地块可能具有相同的 Y 轴刻度。我正在寻找的是在一个图中有两个不同的 Y-aix 比例。
  • 这很清楚。但是,正如解决方案中所述(上面提供的链接),您必须自己缩放值。这可以通过乘法、除法或减法来完成。我在回答中添加了一个示例。
猜你喜欢
  • 2020-09-30
  • 1970-01-01
  • 2012-06-13
  • 1970-01-01
  • 1970-01-01
  • 2017-05-29
  • 2019-04-17
  • 2021-05-07
  • 1970-01-01
相关资源
最近更新 更多