[英]Legend for bar chart with horizontal bars
我正在使用ggplot2
生成条形图,我想在同一张图上包括主要结果以及“黄金标准”。 我尝试了几种方法,但无法为图表生成适当的图例。
在这里,我将geom_col()
用于主要结果,并将geom_errorbar()
用于“黄金标准”。 我不知道如何显示简单的图例(红色=金色标准,蓝色=得分)以匹配此图表。 此外,我不喜欢误差线与1.00处的轴线网格线重叠(而不是完全符合)。
chart_A_data <- data_frame(students= c("Alice", "Bob", "Charlie"),
score = c(0.5, 0.7, 0.8),
max_score = c(1, 1 , 1))
chart_A <- ggplot(chart_A_data, aes(x = students, y = score)) +
geom_col(fill = "blue") +
geom_errorbar(aes(ymin = max_score, ymax = max_score),
size = 2, colour = "red") +
ggtitle("Chart A", subtitle = "Use errorbars to show \"gold standard\"")
chart_A
在这里,我创建了虚拟变量,并使用geom_bar()
生成了堆叠的条形图,然后使未使用的虚拟变量透明。 我对这种方法的精确程度感到满意,但是我不知道如何从图例中删除未使用的哑变量。 另外,在这种情况下,我需要将1.00的任何分数视为特例(即,将其设置为0.99以为“黄金标准”留出空间)。
chart_B_data <- chart_A_data %>%
select(-max_score) %>%
# create dummy variables for stacked bars, note: error if score>0.99
mutate(max_score_line = 0.01) %>%
mutate(blank_fill = 0.99 - score) %>%
gather(stat_level, pct, -students) %>%
# set as factor to control order of stacked bars
mutate(stat_level = factor(stat_level,
levels = c("max_score_line", "blank_fill", "score"),
labels = c("max", "", "score")))
chart_B <- ggplot(data = chart_B_data,
aes(x = students, y = pct, fill = stat_level, alpha = stat_level)) +
geom_bar(stat = "identity", position = "stack") +
scale_fill_manual(values = c("red", "pink", "blue")) +
scale_alpha_manual(values = c(1,0,1)) +
ggtitle("Chart B", subtitle = "Create dummy variables and use stacked bar chart")
chart_B
我不介意是否应该采用完全不同的方法来处理此问题,但是我真的很希望能够在条形图上显示带有简单明了图例的黄金标准。 我将编写一个脚本来处理这些图表的50-60,因此我不想考虑太多“特殊情况”。
如果只有一个max score
:这可能看起来有点怪(也许不是那么漂亮),但是可以做到这一点:
ggplot(chart_A_data, aes(x = students, y = score))+
geom_col()+
geom_hline(yintercept = chart_A_data$max_score)
另一个:
ggplot(chart_A_data, aes(x = students,
y = score,
fill = students))+
geom_col()+
geom_segment(aes(x = as.numeric(students)-.15,
xend = as.numeric(students)+.15,
y = max_score,
yend = max_score,
color = students))
在这种情况下,每个学生的最高分数都有变化(您可能需要使用硬编码的0.15
玩,直到找到合适的东西):
ggplot(chart_A_data, aes(x = students,
y = score))+
geom_col(aes(fill = "blue"))+
geom_segment(aes(x = as.numeric(students)-.25,
xend = as.numeric(students)+.25,
y = max_score,
yend = max_score, color = "red"),
size = 1.7)+
scale_fill_identity(name = "",
guide = "legend",
labels = "Score")+
scale_color_manual(name = "",
values = ("red" = "red"),
labels = "Max Score")
产生:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.