我有一个带有来自 ggplot 的平滑线的条形图。但由于某种原因,蓝线出现在条形图颜色顶部的图例中,我不明白它们来自哪里以及如何删除它们。特别是因为它是蓝色的阴影,我没有在代码中使用。
这是我的代码。我尝试过各种 ggplot 函数,例如
show_guide = F
或 override.aes
,但它们要么不起作用,要么完全删除图例。
# Combine both lists into a data frame
anomaly_mean <- data.frame(
Year = rep(1980:2023, each = 2), # Years for x-axis, repeat years twice for DWD and ERA5
Anomaly = c(D.anomaly_mean, E.anomaly_mean), # Combined anomalies
Dataset = rep(c("DWD", "ERA5"), times = length(D.anomaly_mean)) # Dataset names
)
# Create a new column combining Dataset and Anomaly sign
anomaly_mean$ColorGroup <- with(anomaly_mean, paste(Dataset, ifelse(Anomaly >= 0, "+", "-"), sep = ""))
# Plot barplot for Mean Anomalies
ggplot(anomaly_mean, aes(x = factor(Year), y = Anomaly, fill = ColorGroup, group = Dataset)) +
geom_bar(stat = "identity", position = "dodge") +
geom_smooth(data = subset(anomaly_mean, Dataset == "DWD"),# Smoothing line for DWD
method = "loess", aes(x = factor(Year), y = Anomaly, color = "DWD"),
size = 1, se = FALSE, span = 0.4) +
geom_smooth(data = subset(anomaly_mean, Dataset == "ERA5"), # ERA5 line in blue
method = "loess", aes(x = factor(Year), y = Anomaly, color = "ERA5"),
size = 1, se = FALSE, span = 0.4) +
labs(title = "Anomalies for yearly mean temperatures",
subtitle = "Reference Period from 1981 to 2010; computed from DWD and ERA5 Data",
x = "Year",
y = "Temperature Anomaly [°C]",
color = "LOESS") + # Title for the line legend
scale_fill_manual(values = c("DWD+" = "brown2",
"DWD-" = "cornflowerblue",
"ERA5+" = "darkred",
"ERA5-" = "blue")) +
scale_color_manual(values = c("DWD" = "gray", "ERA5" = "black")) + # colors for the smoothing lines
theme_minimal() +
theme(plot.title = element_text(hjust = 0.5),
plot.subtitle = element_text(hjust = 0.5, size = 10),
panel.grid.major = element_blank(),
panel.grid.minor = element_blank(),
legend.title = element_text(size = 10),
legend.key.size = unit(0.5, "cm")) +
scale_x_discrete(labels = function(x) ifelse(as.integer(x) %% 5 == 0, x, "")) # Show only every 5 years
艾伦·卡梅伦的评论很好地回答了你的问题。 正确的代码片段在这里:
ggplot(anomaly_mean, aes(x = factor(Year), y = Anomaly, group = Dataset)) +
geom_bar(aes(fill = ColorGroup), stat = "identity", position = "dodge") + # here is the change
geom_smooth(data = subset(anomaly_mean, Dataset == "DWD"),
method = "loess", aes(x = factor(Year), y = Anomaly, color = "DWD"),
size = 1, se = FALSE, span = 0.4) +
geom_smooth(data = subset(anomaly_mean, Dataset == "ERA5"),
method = "loess", aes(x = factor(Year), y = Anomaly, color = "ERA5"),
size = 1, se = FALSE, span = 0.4)