R语言 如何分离双轴ggplot的两个重叠图例,一个图例用形状表示变量,另一个用颜色表示组?

x6h2sr28  于 2023-01-10  发布在  其他
关注(0)|答案(1)|浏览(347)

我有以下 Dataframe 作为reprex:

weather <- data.frame(time= c("12:19","12:15","13:20","13:22","16:19"), sensor_rh = c("A","B","C","A","A"), sensor_t = c("A","B","C","C","A"), t = c(30.4,29.4,29.4,30.3,28.9), rh = c(66.8,67.1,67.6,67.1,68.0))

我希望图中显示两种不同的形状,区分rh和t变量,以及三种颜色,区分rh和t的传感器。
我正在设法绘制散点图中所需的点,主轴为可变相对湿度(rh),次轴为可变温度(temp)。然而,作为一个例子,下面的代码没有给我两个单独的图例;一个用于变量,一个用于传感器。

scale <- 2
ggplot(weather, aes(x = time)) +
  geom_point(aes(y = rh, color = sensor_rh), shape = 1) +
  geom_point(aes(y = t*scale, color = sensor_t), shape = 3) +
  scale_color_manual(name = "sensor", values = c("A" = "red", "B" = "blue", "C" = "green"), guide = guide_legend(title = "Sensor", title.position = "top", title.hjust = 0.5 )) +
  scale_shape_manual(name = "variable", values = c("rh" =1, "t" = 3), guide = guide_legend(title = "variable", title.position = "top", title.hjust = 0.5)) +
  scale_y_continuous(name = "rh(%)", sec.axis = sec_axis(~./scale, name = "t(°C)")) + 
  labs(x= "time")

scatterplot with dual axis only one (overlapping)legend
有没有人能帮我找出如何绘制所需的图形?我觉得我已经玩了这么多的方式与代码,与问题似乎几乎重复到我的,但大多数我要么没有得到正确绘制的散点或我没有得到一个单独的图例。
看起来这两个变量的形状是重叠的。
我知道在使用双轴方面存在争议,但请不要在这里进行讨论。
先谢谢你!

wkyowqbh

wkyowqbh1#

不要将形状设置为shape美学上的参数Map,即在aes()内部。因为已经包含了scale_shape_manual,所以可以在geom_point层中使用shape="rh"shape="t"

library(ggplot2)

scale <- 2
ggplot(weather, aes(x = time)) +
  geom_point(aes(y = rh, color = sensor_rh, shape = "rh")) +
  geom_point(aes(y = t * scale, color = sensor_t, shape = "t")) +
  scale_color_manual(
    name = "sensor", values = c("A" = "red", "B" = "blue", "C" = "green"),
    guide = guide_legend(title = "Sensor", title.position = "top", title.hjust = 0.5)
  ) +
  scale_shape_manual(
    name = "variable", values = c("rh" = 1, "t" = 3),
    guide = guide_legend(title = "variable", title.position = "top", title.hjust = 0.5)
  ) +
  scale_y_continuous(name = "rh(%)", sec.axis = sec_axis(~ . / scale, name = "t(°C)")) +
  labs(x = "time")

相关问题