我正在编写一个脚本,为参加考试/调查的每所学校生成统计报告。
为此,我希望能够根据每个学校的具体数据自动调整图形中x和y轴的范围。
例如,我希望百分比范围显示在可用的特定数据以下5%和5%以上。
例如,我有以下图形:
library(ggplot2)
library(scales)
example1 <- data.frame(stringsAsFactors=FALSE,
ID = c("Skole", "Land", "Skole", "Land", "Skole", "Land"),
value = c(0.654590909090909, 0.528446335193598, 0.631238336316461,
0.550262048394226, 0.669981060606061, 0.502430105282051),
variable = as.factor(c("Measurement and Geometry(Applying)",
"Measurement and Geometry(Applying)",
"Measurement and Geometry(Knowing)",
"Measurement and Geometry(Knowing)",
"Measurement and Geometry(Reasoning)",
"Measurement and Geometry(Reasoning)")))
item <- ggplot(example1, aes(x=variable, y=value, fill=ID)) +
geom_bar(stat="identity", position = position_dodge()) +
labs (y = "Procentdel rigtige besvarelser", title = "Matematik", x="Fagområde") +
scale_fill_manual(values=c("grey","blue")) +
coord_flip() +
guides(fill = guide_legend(reverse = TRUE)) +
theme(legend.title = element_blank()) +
scale_y_continuous(labels = percent)
item
以下是示例图片:
谢谢!
答案 0 :(得分:0)
这是一个笨拙的变体,通过计算最小值和最大值,然后将ylim
控制在coord_flip
内。
library(tidyverse)
data.frame(stringsAsFactors=FALSE,
ID = c("Skole", "Land", "Skole", "Land", "Skole", "Land"),
value = c(0.654590909090909, 0.528446335193598, 0.631238336316461,
0.550262048394226, 0.69981060606061, 0.502430105282051),
variable = as.factor(c("Measurement and Geometry(Applying)",
"Measurement and Geometry(Applying)",
"Measurement and Geometry(Knowing)",
"Measurement and Geometry(Knowing)",
"Measurement and Geometry(Reasoning)",
"Measurement and Geometry(Reasoning)"))) %>%
mutate(low = min(value) - min(value) * 0.05,
high = max(value) + max(value) * 0.05) -> example1
example1 %>%
ggplot(aes(variable, value, fill=ID)) +
geom_bar(stat="identity", position = position_dodge()) +
labs (y = "Procentdel rigtige besvarelser", title = "Matematik", x="Fagområde") +
scale_fill_manual(values=c("grey","blue")) +
guides(fill = guide_legend(reverse = TRUE)) +
theme(legend.title=element_blank()) +
coord_flip(ylim=c(mean(test$low), mean(test$high)))