英文:
Side by side barplots in r
问题
我想创建并列的柱状图,以显示两个等级之间的差异,我构想的是这样的
任何帮助都将不胜感激。
英文:
I have a data set that looks like this
I want to create side by side barplots that will show the differences between the two grades, I envisioned something like this
Any help would be highly appreciated.
答案1
得分: 1
在基本的R中,您可以使用barplot
通过一系列的par(new = TRUE)
和ifelse
逻辑来迭代地叠加值。您可以使用类似的逻辑使用text
来添加文本:
par(mfrow = c(1,2)) # 并排绘图
# 左侧图
barplot(df$Grade_Semester1, names.arg = df$Person, horiz = TRUE, col = "grey", xlim = c(0, 10))
# 右侧图
barplot(ifelse(df$Difference < 0, df$Grade_Semester1, 0),
names.arg = df$Person, horiz = TRUE, col = "red", xlim = c(0, 10))
par(new = TRUE)
barplot(ifelse(df$Difference > 0, df$Grade_Semester2, 0),
names.arg = df$Person, horiz = TRUE, col = "green", xlim = c(0, 10))
par(new = TRUE)
xx <- barplot(pmin(df$Grade_Semester1, df$Grade_Semester2),
names.arg = df$Person, horiz = TRUE, col = "grey", xlim = c(0, 10))
text(pmin(df$Grade_Semester1, df$Grade_Semester2) + abs(pmin(df$Difference)/2),
xx, ifelse(df$Difference == 0, "", ifelse(df$Difference > 0, paste0("+", df$Difference), df$Difference)))
数据:
df <- data.frame(Person = c("A", "B", "C"),
Grade_Semester1 = c(9, 10, 8),
Grade_Semester2 = c(7, 10, 10),
Difference = c(-2, 0, 2))
英文:
In base R, you can use barplot
to iteratively lay over the values through a series of par(new = TRUE)
and ifelse
logic. You can add the text with similar logic using text
:
par(mfrow = c(1,2)) #side by side plot
# left plot
barplot(df$Grade_Semester1, names.arg = df$Person, horiz = TRUE, col = "grey", xlim = c(0, 10))
# right plot
barplot(ifelse(df$Difference < 0, df$Grade_Semester1, 0),
names.arg = df$Person, horiz = TRUE, col = "red", xlim = c(0, 10))
par(new = TRUE)
barplot(ifelse(df$Difference > 0, df$Grade_Semester2, 0),
names.arg = df$Person, horiz = TRUE, col = "green", xlim = c(0, 10))
par(new = TRUE)
xx <- barplot(pmin(df$Grade_Semester1, df$Grade_Semester2),
names.arg = df$Person, horiz = TRUE, col = "grey", xlim = c(0, 10))
text(pmin(df$Grade_Semester1, df$Grade_Semester2) + abs(pmin(df$Difference)/2),
xx, ifelse(df$Difference == 0, "", ifelse(df$Difference > 0, paste0("+", df$Difference), df$Difference)))
Data
df <- data.frame(Person = c("A", "B", "C"),
Grade_Semester1 = c(9, 10, 8),
Grade_Semester2 = c(7, 10, 10),
Difference = c(-2, 0, 2))
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论