GGPLOT2下降从离散图例项

时间:2019-01-30 15:38:01

标签: r ggplot2

使用离散在ColorBrewer颜色我GGPLOT2图例犯规显示所有正在使用geom_line绘制的水平。具有审核类似的问题上StackExchange伊夫尝试添加一滴= FALSE到两个scale_colour_distiller但这并不解决问题。

我在这里做错了什么?下面重复的代码

谢谢

迈克

library(tidyverse)

Year <- c(2012, 2012, 2012, 2012, 2012, 2012, 2012, 2012, 2012, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2013, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2014, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2015, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2016, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2017, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2018, 2019)
Month <- c(4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1, 2, 3, 4, 5, 6, 7, 8, 9, 10, 11, 12, 1)
Cum_Total <- c(0,0,0,0,0,0,0,0,0,0,0, 14558, 14568, 14674, 14757, 14807, 14902, 14950, 15024, 15049, 15203, 14775, 14906, 14905, 14991, 15004, 15055, 15112, 15170, 15166, 15273, 15417, 15581, 14939, 15028, 15038, 15127, 15222, 15286, 15395, 15418, 15476, 15528, 15507, 15589, 14919, 15021, 15056, 15115, 15137, 15176, 15176, 15248, 15229, 15277, 15269, 15402, 14839, 14849, 14912, 14929, 14913, 14948, 15015, 15022, 15096, 15046, 15089, 15115, 14737, 14700, 14733, 14694, 14767, 14804, 14730, 14752, 14943, 14918, 14937, 14664, 13081)
Cum_Total[Cum_Total == 0] <- NA
results <- data.frame(Year,Month,Cum_Total)

ggplot(results,aes(x=Month,y=Cum_Total, group=Year, color=Year)) +
  geom_line() +
  geom_point() +
  scale_colour_distiller(palette = "Dark2", direction=-1, guide="legend") +
  scale_y_continuous(name="Cumulative Total", limits=c(13000,16000)) +
  scale_x_continuous(name="Month", limits=c(1, 12), breaks=c(2,4,6,8,10,12))

1 个答案:

答案 0 :(得分:3)

使用breaks指定要显示的所有年份。

ggplot(results,aes(x=Month,y=Cum_Total, group=Year, color=Year)) +
  geom_line() +
  geom_point() +
  scale_colour_distiller(palette = "Dark2", breaks = unique(results$Year),
                         direction = -1, guide = "legend") +
  scale_y_continuous(name="Cumulative Total", limits=c(13000,16000)) +
  scale_x_continuous(name="Month", limits=c(1, 12), breaks=c(2,4,6,8,10,12))

enter image description here

或将年份更改为factor,然后使用scale_colour_brewer

ggplot(results,aes(x=Month,y=Cum_Total, group=Year, color = factor(Year))) +
  geom_line() +
  geom_point() +
  scale_colour_brewer(palette = "Dark2", direction = -1, guide = "legend") +
  scale_y_continuous(name="Cumulative Total", limits=c(13000,16000)) +
  scale_x_continuous(name="Month", limits=c(1, 12), breaks=c(2,4,6,8,10,12)) 

enter image description here