首页 > 解决方案 > 使用 scale_color_binned(guide = guide_legend()) 时缺少一些图例项

问题描述

我使用以下代码绘制折线图。当我将连续颜色图例转换为离散图例时,缺少一些图例键。

df <- data.frame(L = seq(from=30, t =300, by=10), Kg = rep(22427983, length=28),
                 t = rep(10, length=28), de = rep(3.33, length=28))
S <- c(8,10,12,14,16)
df <- merge(df,S)
colnames(df)[5] <- "S"

Span_M.E.M <- data.frame(df, Current = (0.77 + (df$de/9.1)) * (0.075 + (df$S/9.5)^0.6 *
                         (df$S/df$L)^0.2 * (df$Kg/(12 * df$L * (df$t)^3))^0.1), Updated =
                          0.1 + 1.15 * (0.77 + (df$de/9.1)) * (0.075 + (df$S/9.5)^0.6 *
                         (df$S/df$L)^0.2 * (df$Kg/(12 * df$L * (df$t)^3))^0.1))
ggplot(Span_M.E.M, aes(L, colour = S, group = S)) +
 geom_line(aes(y = Current, linetype = "Current")) +
 geom_line(aes(y = Updated, linetype = "Updated")) +
 scale_color_gradient() +
 labs(x = element_text("Span Length (ft)"), y = element_blank(), 
         title = paste("Moment Live Load Distribution Factors \n Exterior Girder - Multi Lane"),
      linetype = element_blank(), color = "Spacing (ft):") +
  scale_linetype_manual(values = c(1, 2),
                        labels = c("Updated","Current")) +
    theme_classic() +
    theme(plot.title = element_text(hjust = 0.5, margin = margin(45,0,20,0), size = 18),
          legend.position="top",
          legend.box.background = element_rect(colour = "black", size = 0.5),
          legend.box.margin = margin(0,0,0,0), legend.background = element_blank()) +
  scale_color_binned(guide = guide_legend(), type = "viridis")

应该有 5 种不同的颜色显示,但图例中只打印了三种颜色。 在此处输入图像描述

标签: rggplot2

解决方案


尝试这个:

library(ggplot2)

ggplot(Span_M.E.M, aes(L, colour = S, group = S)) +
  geom_line(aes(y = Current, linetype = "Current")) +
  geom_line(aes(y = Updated, linetype = "Updated")) +
  scale_colour_continuous(guide = guide_legend(), type = "viridis") +
  labs(x = element_text("Span Length (ft)"), y = element_blank(), 
       title = paste("Moment Live Load Distribution Factors \n Exterior Girder - Multi Lane"),
       linetype = element_blank(), color = "Spacing (ft):") +
  scale_linetype_manual(values = c(1, 2),
                        labels = c("Updated","Current")) +
  theme_classic() +
  theme(plot.title = element_text(hjust = 0.5, margin = margin(45,0,20,0), size = 18),
        legend.position="top",
        legend.box.background = element_rect(colour = "black", size = 0.5),
        legend.box.margin = margin(0,0,0,0), legend.background = element_blank())

推荐阅读