ggplot R 中两个辅助轴 y 的两个数据集

时间:2021-03-25 10:25:20

标签: r ggplot2 axis

第一个数据集 = df

Date variable value 
1    A          6
1    B          2
1    C          0.8
2    A          8
2    B          3
2    C          2
3    A          11
3    B          2
3    C          4

第二个数据集 = 满足

Date variable value
 1     H       140.000
 2     H       70.000
 3     H       150.000

我正在做什么,但它不起作用

  ggplot() 
+ geom_line(df, mapping = aes(x=date, y=value, fill=variable, color = variable, linetype=variable)) 
+ geom_line(met, mapping = aes(x=date,y=value, color="blue")) 
+ scale_y_continuous(name = "First Axis", sec.axis = sec_axis(~.1, name="Second Axis"))
      
Error: Discrete value supplied to continuous scale
Warning message: 
Ignoring unknown aesthetics: fill 

同时我还有一个问题。可以设置 2 ylim 吗?一个用于左侧,另一个用于右侧。

提前致谢

1 个答案:

答案 0 :(得分:0)

您已经很接近了,但是您的代码中有一些小错误:

  1. R 区分大小写,因此 Datedate 不同。
  2. 对为 sec_axis 转换提供公式的语法稍作调整
  3. 如果您要修复美学而不是映射到数据变量(例如 color = "blue"color = variable),那么您可能希望将其放在 aes() 之外以避免创建图例为了它。除非这是您的意图,否则请忽略这一点。
  4. 如果您要转换第二个轴以按不同比例显示某些数据,您可能也需要转换该数据。因此,您将在第二个 geom_line 层中看到我将 y = 10*value 设置为补偿。

回答您关于 2 个不同 ylim 值的问题 - 没有。第二个轴是第一个轴的线性变换,其极限需要与第一个轴的极限相同。显示的数字只是一个显示值。如果要更改限制,则需要在单独的图中,例如带有 scales = "free_y"faceted plot

# load packages
library(tidyverse)

# set up data
df <- structure(list(Date = c(1L, 1L, 1L, 2L, 2L, 2L, 3L, 3L, 3L), 
                     variable = c("A", "B", "C", "A", "B", "C", "A", "B", "C"), 
                     value = c(6, 2, 0.8, 8, 3, 2, 11, 2, 4)), class = "data.frame", row.names = c(NA, 
                                                                                                   -9L))
met <- structure(list(Date = 1:3, variable = c("H", "H", "H"), value = c(140, 
                                                                         70, 150)), class = "data.frame", row.names = c(NA, -3L))
# plot calling each dataset in separate geom layers
ggplot() +
  geom_line(df,
            mapping = aes(
              x = Date,
              y = 10 * value,
              color = variable,
              linetype = variable
            )) +
  geom_line(met, mapping = aes(x = Date, y = value), color = "blue") +
  scale_y_continuous(name = "First Axis",
                     sec.axis = sec_axis( ~ . * .1, name = "Second Axis"))

reprex package (v1.0.0) 于 2021 年 3 月 25 日创建