使用不同的颜色或线型R绘制线

时间:2018-07-18 15:38:08

标签: r ggplot2 data-visualization

我正面临数据可视化问题。这是我的数据的一部分:

head(Dataset) 

Project    Date             Budget   Project Status
PR1      September 2015     0.2        Ongoing
PR1      October 2015       0.5        Ongoing
PR1      November 2015      0.9        Ongoing
PR1      December 2015      1.2        Ongoing 
PR1      January 2016       1.8        Suspended
PR1      February 2016      1.8        Suspended
PR1      March 2016         1.8        Abandoned   
PR2      August 2015        1.5        Ongoing
PR2      September 2015     1.9        Ongoing
PR2      October 2015       2.3        Ongoing
PR2      December 2015      2.5        Ongoing
PR2      January 2016       2.8        Ended

我想根据状态修改来绘制每个项目的预算变化。我尝试了以下代码

 g1 <- ggplot(Dataset, aes(Dataset$Date, Dataset$Budget))+
 geom_line(color=Dataset$Project, linetype=Dataset$Status)

但是我遇到了这个错误:

Error: geom_path: If you are using dotted or dashed lines, colour, size and linetype must be constant over the line

你能告诉我吗?

非常感谢!

1 个答案:

答案 0 :(得分:3)

下面的注释整理了数据值(年,月,项目状态)的命名方式

Dataset <- read.table(text="
Project  Month     Year      Budget     Project_Status
PR1      September 2015     0.2        Ongoing
PR1      October 2015       0.5        Ongoing
PR1      November 2015      0.9        Ongoing
PR1      December 2015      1.2        Ongoing 
PR1      January 2016       1.8        Suspended
PR1      February 2016      1.8        Suspended
PR1      March 2016         1.8        Abandoned   
PR2      August 2015        1.5        Ongoing
PR2      September 2015     1.9        Ongoing
PR2      October 2015       2.3        Ongoing
PR2      December 2015      2.5        Ongoing
PR2      January 2016       2.8        Ended
", header=TRUE)

library(lubridate)

# Make date a true date type, using lubridate conversions
Dataset$Date = dmy(paste("1", Dataset$Month, Dataset$Year))

# Plot with the dataset sepecified once (cleaner)
g1 <- ggplot(Dataset, aes(x=Date, y=Budget)) +
  # draw line for the budget coloring by project
  geom_line(aes(color=Project))  +
# draw a point overlay for the stautus at that point in time
  geom_point(aes(shape=Project_Status))
print(g1)

enter image description here