如何为项目符号图表添加自定义图例

时间:2017-12-29 09:05:45

标签: r ggplot2

我有以下数据集:

incidents.pct <- data.frame(
  measure=c("Total Events (%)", "Security Events (%)", "Filtered (%)", "Tickets (%)"),
  high=c(100,100,100,100),
  mean=c(45,40,50,30),
  low=c(25,20,10,5), 
  target=c(55,40,45,35),
  value=c(50,45,60,25))

我用它来创建以下“子弹般的”图形。

g <- ggplot(incidents.pct) +
  geom_bar(aes(measure, high),  fill="goldenrod2", stat="identity", width=0.5, alpha=0.2) +
  geom_bar(aes(measure, mean),  fill="goldenrod3", stat="identity", width=0.5, alpha=0.2) +
  geom_bar(aes(measure, low),   fill="goldenrod4", stat="identity", width=0.5, alpha=0.2) +        
  geom_point(aes(measure, target), colour="red", size=2.5) 

这很有效,但是我希望包含一个解释颜色的自定义图例。所以只是一个带有“低”,“中等”,“价值”等的颜色标志......

有关如何包含此内容的任何建议吗?

3 个答案:

答案 0 :(得分:5)

在ggplot中,如果它位于aes()内,则会自动为美学选项生成图例。因此,scale_fill_manual()的以下解决方法将为您提供一个图例:

ggplot(incidents.pct) +
  geom_col(aes(measure, high, fill = "high"), width=0.5, alpha=0.2) +
  geom_col(aes(measure, mean, fill = "mean"), width=0.5, alpha=0.2) +
  geom_col(aes(measure, low, fill = "low"), width=0.5, alpha=0.2) +        
  geom_point(aes(measure, target), colour="red", size=2.5) +
  scale_fill_manual(name = "Legend",
                    values = c("high" = "goldenrod2", 
                               "mean" = "goldenrod3", 
                               "low" = "goldenrod4"),
                    breaks = c("high", "mean", "low"))

(顺便说一下,geom_col()相当于geom_bar(stat = "identity"),而且看起来更整洁。

plot

我会警告不要在重叠条上使用低alpha值,但是,因为图例的颜色与图表的颜色不完全匹配。选择三种较浅的色调会更清晰,并将alpha保留为1。

答案 1 :(得分:1)

另一种选择可能是在绘图之前重塑您的数据。

<select class="form-control" id="group_id" name="group_id" 
    ng-model="form.group" 
    ng-options="match_group as match_group.name for match_group in match_groups"  
    required="" ng-change="getGroupWiseMatches()">
    ....some code
</select>

输出图是: enter image description here

form.group

答案 2 :(得分:0)

似乎我有点晚了@Z.Lin的答案很好,但我也发布了我的帖子,因为我认为它指出了ggplot2的优点,即使用长数据。一旦你的数据整齐,就很容易打印(是的,它需要更多行来转换数据; - )):

incidents.pct %>% 
  # ggplot2 likes long data:
  gather(key = key, value = val, high, mean, low) %>% 
  # give nice order to factors:
  mutate(key = factor(key, levels = c("high", "mean", "low"))) %>% 
  # arrange and group to take difference such that we can stack the values (sum up to 100):
  arrange(measure, desc(key)) %>% 
  group_by(measure) %>% 
  mutate(val = val-ifelse(is.na(lag(val)), 0, lag(val))) %>% 
  # plot it, giving aes in ggplot, not necessarily below:
  ggplot(aes(x = measure, y = val, fill = key)) +
  # use geom_col if you want to use identity anyway:
  geom_col(width = .5, alpha = .2) +
  # just change the y-value in the aes, don't add it to legend:
  geom_point(aes(y = target), colour = "red", size = 2.5, show.legend = FALSE) +
  # now define your colours:
  scale_fill_manual(values = c("goldenrod2", "goldenrod3", "goldenrod4"))