所以我有一个两个 Y 轴图。每个 Y 轴都有一组数据。
我想在第二张图片所示位置的图的左侧和右侧为每个组有两个不同的图例。
这是我正在使用的代码:
coeff <- .025
Plot <- ggplot(df_visual_count_average, aes(x=cym)) +
geom_line(aes(y = count_cont_res, color = "Count Cat1"), group = 1, size = 1.5) +
geom_line(aes(y = count_fos_car, color = "Count Cat2"), group = 2, size = 1.5 ) +
geom_line(aes(y = count_oth, color = "Count Cat3"), group = 3, size = 1.5) +
geom_line(aes(y = count_SHSS_cont_res, color = "Count Cat4"), group = 4, size = 1.5) +
geom_line(aes(y = ave_age_cont_res/coeff, color = "Ave age of Cat5"), group = 1, size = 1.5) +
geom_line(aes(y = ave_age_fos_car/coeff, color = "Ave age of Cat6"), group = 2, size = 1.5 ) +
geom_line(aes(y = ave_age_oth/coeff, color = "Ave age Cat7"), group = 3, size = 1.5) +
geom_line(aes(y = ave_age_SHSS_cont_res/coeff, color = "Ave age Cat8"), group = 4, size = 1.5) +
scale_y_continuous( name = "Counts of Group1", sec.axis = sec_axis(~.*coeff, name="Average of Group 2") ) +
ggtitle("Counts and Average of Group variation with time")
剧情
ggnewscale 软件包允许您添加已在使用的其他秤。
library(ggplot2)
library(ggnewscale)
pivot_longer(df_visual_count_average, -cym,
names_to=c(".value", "name"),
names_pattern="(count|ave_age)_(.*)") |>
ggplot(aes(x=cym)) +
geom_line(aes(y = count, color = name), size = 1.5) +
labs(color="Average of Group 2") +
new_scale_color() +
geom_line(aes(y = ave_age/coeff, color=name), size = 1.5) +
scale_y_continuous(name = "Counts of Group 1",
sec.axis = sec_axis(~.*coeff, name="Average of Group 2") ) +
scale_color_manual(values=c("blue","green4","brown","orange")) +
ggtitle("Counts and Average of Group variation with time") +
guides(col=guide_legend(title="Count of Group 1", position="left"))
df_visual_count_average <- data.frame(
cym=seq(2000,2024),
count_cont_res=rnorm(25, 600, 100),
count_fos_car=rnorm(25, 500, 100),
count_oth=rnorm(25, 400, 50),
count_SHSS_cont_res=rnorm(25, 300, 50),
ave_age_cont_res=rnorm(25, 40, 5),
ave_age_fos_car=rnorm(25, 30, 5),
ave_age_oth=rnorm(25, 20, 5),
ave_age_SHSS_cont_res=rnorm(25, 10, 5)
)