[英]coloring legend in bar chart in R
I'm faily new to R and do need some help in manipulating my graph. 我对R不熟悉,在操作图形时确实需要一些帮助。 I'm trying to compare actual and forecast figures, but cannot get the coloring of the legends right.
我正在尝试比较实际数字和预测数字,但无法正确显示图例的颜色。 The data looks like this:
数据如下所示:
hierarchy Actual Forecast
<fctr> <dbl> <dbl>
1 E 9313 5455
2 K 6257 3632
3 O 7183 8684
4 A 1579 6418
5 S 8755 0149
6 D 5897 7812
7 F 1400 8810
8 G 4960 5710
9 R 3032 0412
And the code looks like this: 代码看起来像这样:
ggplot(sam4, aes(hierarchy))+ theme_bw() +
geom_bar(aes(y = Actual, colour="Actual"),fill="#66FF33", stat="identity",position="dodge", width=0.40) +
geom_bar(aes(y = Forecast, colour="Forecast"), fill="#FF3300", stat="identity",position="dodge", width=0.2)
The graph ends up looking like this: 该图最终看起来像这样:
I believe your problem is that your data is not formatted well to use ggplot. 我相信您的问题是您的数据格式不正确,无法使用ggplot。 You want to tidy up your dataframe first.
您想先整理一下数据框。 Check out http://tidyr.tidyverse.org/ to get familiar with the concept of tidy data.
请访问http://tidyr.tidyverse.org/以熟悉整洁数据的概念。
Using the tidyverse (ggplot is part of it), I tidied up your data and I believe got the plot you want. 使用tidyverse(ggplot是其中的一部分),我整理了您的数据,并相信得到了想要的绘图。
library(tidyverse) #includes ggplot
newdata <- gather(sam4, actualorforecast, value, -hierarchy)
ggplot(newdata, aes(x = hierarchy)) +
theme_bw() +
geom_bar(aes(y = value, fill = actualorforecast),
stat = "identity",
width = ifelse(newdata$actualorforecast == "Actual", .4, .2),
position = "dodge") +
scale_fill_manual(values= c(Actual ="#66FF33", Forecast="#FF3300"))
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.