为什么ggplot(geom_line)中的颜色与显式分配的颜色不同

时间:2019-04-22 07:52:50

标签: r ggplot2

颜色未按所示绘制,我认为这是一个错误

library(ggplot2)

x <- seq(1,20,1)
market_yield1 <- c(1.00,1.20,1.35,1.50,1.60,1.70,1.75,1.85,1.90,1.95,
                   2.00,2.05,2.08,2.11,2.14,2.17,2.19,2.21,2.23,2.25)
market_yield2 <- c(1.00,1.20,1.35,1.50,1.60,1.70,1.75,1.85,1.85,1.80,
                   1.75,1.70,1.67,1.64,1.60,1.58,1.55,1.52,1.50,1.48)
market_yield3 <- c(1.00,0.98,0.95,0.93,0.91,0.89,0.87,0.84,0.81,0.78,
                   0.76,0.73,0.70,0.68,0.66,0.64,0.63,0.61,0.60,0.58)
x <- seq(1,20,1)
total <- data.frame(x, market_yield1, market_yield2, market_yield3)
names(total)[2:4] <- c("Szenario_1","Szenario_2","Szenario_3")


f <- ggplot(data = total) +
  geom_line(aes(x, Szenario_1, color = "red"), size = 1)+
  geom_line(aes(x, Szenario_2, color = "green"), size = 1)+
  geom_line(aes(x, Szenario_3, color = "blue"), size = 1)+
  labs(x = "Anzahl Jahre n",  y = "Zinsen in %", 
       title ="Die erwarteten Zinskurven",subtitle = "für die 3 Szenarien")+
  scale_color_discrete(name = "Verschiede Szenarien",
                       breaks = c("red","green","blue"),
                       labels = c("Szenario 1","Szenario 2","Szenario 3"))
plot(f)

我希望Szenario_1应该是红色,而Szenario_3应该是蓝色

plot(f)

2 个答案:

答案 0 :(得分:1)

这不是错误。您的数据采用宽格式,并且您正在内部 aes()中分配颜色值。如果要继续使用此方法,请尝试以下操作:

ggplot(data = total) +
  geom_line(aes(x, Szenario_1, color = "red"), size = 1)+
  geom_line(aes(x, Szenario_2, color = "green"), size = 1)+
  geom_line(aes(x, Szenario_3, color = "blue"), size = 1)+
  labs(x = "Anzahl Jahre n",  y = "Zinsen in %", 
       title ="Die erwarteten Zinskurven",subtitle = "für die 3 Szenarien")+

  # use scale_color_manual to specify the actual colours mapping to the values specified
  # within each aes() mapping
  scale_color_manual(name = "Verschiede Szenarien",
                     limits = c("red", "green", "blue"),
                     values = c("red", "green", "blue"),
                     labels = c("Szenario 1", "Szenario 2", "Szenario 3"))

但是更整洁的方法是将数据转换为长格式,并使每个方案都位于同一geom_line层中:

library(dplyr)
library(tidyr)

total %>%
  gather(scenario, value, -x) %>%
  ggplot(aes(x, value, color = scenario)) +
  geom_line(size = 1) +
  labs(x = "Anzahl Jahre n",  y = "Zinsen in %", 
       title ="Die erwarteten Zinskurven",subtitle = "für die 3 Szenarien") +
  scale_color_manual(name = "Verschiede Szenarien",
                     values = c("red", "green", "blue"),
                     labels = c("Szenario 1", "Szenario 2", "Szenario 3"))

plot

(两个代码段都返回相同的结果。)

答案 1 :(得分:0)

一种快速而肮脏的解决方案是将颜色分配从aes中剔除

geom_line(aes(x, Szenario_1), color = "red", size = 1)+
geom_line(aes(x, Szenario_2), color = "green", size = 1)+
geom_line(aes(x, Szenario_3), color = "blue", size = 1)+