改变ggplot中融化的df的颜色

时间:2018-03-07 23:57:52

标签: r ggplot2

我正在尝试更改以下ggplot的颜色,但发现很难这样做......

mm <- melt(CashCycle, id= c('Ticker', 'Date'))
mm <- mm[mm$variable == "CollectionPeriod" | mm$variable == "DaysofInventory" | mm$variable == "DaysofPayable",]
mm$value <- with(mm, ifelse(variable == "DaysofPayable", -value, value))
ggplot(data = mm, aes(x = Date, y = value, fill = variable)) + 
  geom_bar(stat = 'identity', position = 'dodge') +
  labs(x="Year", y="Days") +
  theme_bw() +
  guides(color=guide_legend("Legend"))

我想将条形设置为c("Red", "Blue", "Orange"),但我尝试的所有内容似乎都被覆盖。

dput被称为CashCycle

dput代码:

structure(list(Ticker = c("GOOG", "GOOG", "GOOG", "GOOG", "GE", 
"GE", "GE", "GE", "HOG", "HOG", "HOG", "HOG"), Date = c(2017, 
2016, 2015, 2014, 2017, 2016, 2015, 2014, 2017, 2016, 2015, 2014
), CollectionPeriod = c(61.5878850750981, 57.5447536334633, 67.7003960580885, 
59.9973485250224, 73.0579967729518, 71.0453384212398, 84.0229160454913, 
72.3776710131076, 157.424759439158, 143.734811872338, 140.084289622044, 
126.828872394842), DaysofInventory = c(5.99752100563807, 2.78388069895839, 
0, 0, 84.1604875945267, 89.3934679478049, 96.688883921218, 75.6542499589885, 
57.0743314700106, 50.7784397810473, 60.7847464805146, 44.1958495635379
), DaysofPayable = c(25.119123357392, 21.2011212931869, 25.0253870188894, 
24.7293880614704, 58.1710472344051, 57.7254500235557, 58.7476763065628, 
51.6094654449157, 24.1362278754634, 23.9021892488319, 24.4431638276767, 
19.3838681657801), CashCollectionCycle = c(42.4662827233442, 
39.1275130392348, 42.6750090391992, 35.267960463552, 99.0474371330733, 
102.713356345489, 121.964123660146, 96.4224555271804, 190.362863033705, 
170.611062404553, 176.425872274881, 151.6408537926), DaysofPayableAccExp = c(140.473312419104, 
126.188741533383, 132.501065189604, 132.486074349149, 129.045057268166, 
124.748556528218, 126.496458573546, 105.229078296735, 75.3037584111009, 
70.6634116884237, 71.3490152830795, 60.6347718419888), CashCollectionCycleAccExp = c(-72.8879063383675, 
-65.860107200961, -64.8006691315152, -72.4887258241263, 28.173427099312, 
35.6902498408272, 54.2153413931629, 42.8028426753607, 139.195332498067, 
123.849839964962, 129.520020819479, 110.389950116391)), .Names = c("Ticker", 
"Date", "CollectionPeriod", "DaysofInventory", "DaysofPayable", 
"CashCollectionCycle", "DaysofPayableAccExp", "CashCollectionCycleAccExp"
), row.names = c(NA, -12L), class = "data.frame")

1 个答案:

答案 0 :(得分:2)

使用scale_fill_manual

ggplot(data = mm, aes(x = Date, y = value, fill = variable)) + 
  geom_bar(stat = 'identity', position = 'dodge') +
  scale_fill_manual(values = c("red", "blue", "orange")) +
  labs(x="Year", y="Days") +
  theme_bw() +
  guides(color=guide_legend("Legend"))