如何使用条形图更改填充的颜色

时间:2019-11-22 22:28:11

标签: r

我有一个数据,试图通过颜色显示ValueM的效果

我正在尝试根据值将条形图的颜色更改为特定颜色

我有这样的数据。我的数据有3列,如下所示

df<- structure(list(Data = structure(1:21, .Label = c("A", "AA", "AAA", 
"AAAA", "AAAAA", "B", "BB", "BBB", "BBBB", "BBBBB", "BBBBBB", 
"C", "CC", "CCC", "CCCC", "CCCCC", "CCCCCC", "D", "DD", "DDD", 
"DDDD"), class = "factor"), ValueT = c(0.001587914, 0.001199237, 
0.001348983, 0.006172349, 0.000869159, 0.003436182, 0.00379154, 
0.009769598, 0.031616288, 0.000767774, 0.001147326, 0.00032072, 
0.005689103, 0.001178389, 0.00546371, 0.002440759, 0.000387064, 
0.002106859, 0.00031543, 0.001919942, 0.019214), ValueM = c(3.69e-05, 
0.000294447, 0.000437104, 0.000929987, 0.001269666, 0.001863104, 
0.002111101, 0.002418451, 0.003484984, 0.003552844, 0.003735689, 
0.004071697, 0.004421729, 0.004920956, 0.005209452, 0.008247638, 
0.009816657, 0.01039518, 0.012987002, 0.013272534, 0.016334177
)), class = "data.frame", row.names = c(NA, -21L))

我试图用

等不同方式绘制它
ggplot(data=df, aes(x=Data, y=ValueT,fill = ValueM)) +
  geom_bar(stat="identity",width =0.8)+
  coord_flip()+
  ggtitle("Rotated ordered x-axis")+
  theme_minimal()+
  scale_fill_gradientn(colours = terrain.colors(3),limits = c(min(df$ValueM), max(df$ValueM)))

我希望颜色像这样

enter image description here

可以设置最低的颜色是黄色还是最低的颜色

如果我这样做,什么也没发生

ggplot(data=df, aes(x=Data, y=ValueT,fill = ValueM)) +
  geom_bar(stat="identity",width =0.8)+
  coord_flip()+
  ggtitle("Rotated ordered x-axis")+
  theme_minimal()+
scale_color_gradient(low = 'red', high = 'yellow')

1 个答案:

答案 0 :(得分:0)

您快到了。您只需要将scale_color_gradient更改为scale_fill_gradient

ggplot(data=df, aes(x=Data, y=ValueT, fill = ValueM)) +
  geom_bar(stat="identity",width =0.8) +
  coord_flip() +
  ggtitle("Rotated ordered x-axis") +
  theme_minimal() +
  scale_fill_gradient(high='red', low='yellow')

enter image description here