修复图例标题并更新几何点数据的颜色

问题描述 投票:0回答:1

在我的图中,我无法让我的scale_fill_manual将“lightblue”适当地分配给非活动数据点,但我将“lightcoral”分配给活动点数据没有问题。另外,我无法正确更新点标签的标签。

我的代码:

ylim.prim <- c(0,850) # scale for precipitation
ylim.sec <- c(-15,20) # scale for mean temperature

b <- diff(ylim.prim)/diff(ylim.sec)
a <- ylim.prim[1] - b*ylim.sec[1] 

 ggplot() + theme_bw() +
  geom_bar(data=precip, mapping=aes(x=Year, y=Value, fill=Variable), stat="identity", position="dodge", color="black") +
  geom_point(data=temps, aes(x=Year, y=a+Value*b, color=Variable), size=5, shape=18) +
  
  # Borders for point data
  geom_point(data=temps, aes(y=a + Value*b, x=Year), color="black", size=3, shape=5, stroke=2) +
  
  # Update scale
  scale_y_continuous(name="Total Precipitation (mm) \n", 
                     breaks=c(0,100,200,300,400,500,600,700,800,900), 
                     limits=c(0,900),
                     expand=c(0,0), # to make the bars start at the x-axis
                     sec.axis = sec_axis(~(. - a)/b, name = "Mean Temperature  (°C)")) +
  scale_x_continuous(name="\nYear") +
  theme(axis.text.x = element_text(size=15, colour="black"),
        axis.text.y = element_text(size=15, colour="black"),
        axis.title = element_text(size=15),
        axis.title.y = element_text(size=15),
        legend.text = element_text(size=15),
        legend.title = element_text(size=15),
        axis.ticks = element_line(linewidth=1),
        axis.title.y.right = element_text(angle=90)) +

 # Assign color and labels to legend
  scale_fill_manual(labels=c("Active","Non-Active","Active","Non-Active"),
                    values=c("lightcoral","lightblue","lightcoral","lightblue"),
                    name=c("Precipitation","Temperature"))

> dput(precip)
structure(list(Year = c(2020L, 2020L, 2021L, 2021L, 2022L, 2022L, 
2023L, 2023L), Variable = c("Precip.x", "Precip.y", "Precip.x", 
"Precip.y", "Precip.x", "Precip.y", "Precip.x", "Precip.y"), 
    Value = c(737, 805, 789.8, 612.8, 611.3, 710.5, 802.7, 753.5
    )), row.names = c(NA, -8L), class = c("tbl_df", "tbl", "data.frame"
))

> dput(temps)
structure(list(Year = c(2020L, 2020L, 2021L, 2021L, 2022L, 2022L, 
2023L, 2023L), Variable = c("Temp.x", "Temp.y", "Temp.x", "Temp.y", 
"Temp.x", "Temp.y", "Temp.x", "Temp.y"), Value = c(17.081043956044, 
3.2175, 17.6239554317549, 3.48527777777778, 17.1328402366864, 
1.54847645429363, 17.3330578512397, 3.79614325068871)), row.names = c(NA, 
-8L), class = c("tbl_df", "tbl", "data.frame"))

我的情节。蓝色的几何点不是正确的蓝色,但红色似乎是我想要的“lightcoral”。我希望点颜色与条形颜色相匹配。图例中的标题似乎没有针对几何点数据进行更新。

enter image description here

ggplot2
1个回答
0
投票

如果我理解正确,您将需要填充和颜色的比例,如下所示:

 scale_fill_manual(labels=c("Active","Non-Active"),
 values=c("lightcoral","lightblue"),
 name="Precipitation")  +

scale_color_manual(labels=c("Temp.x","Temp.y"),
 values=c("lightcoral","lightblue"),
 name="Temperature")
© www.soinside.com 2019 - 2024. All rights reserved.