我正在尝试创建一个带有数据标签的简单分组柱状图,我面临的问题是标签未正确显示。请看下面的截图:
这里的另一个问题是,在添加 geom_text() 语句后,我在最右侧的图例上方和下方出现了 2 个不需要的项目,即大小和颜色
使用的数据
data<-structure(list(survey_period = c("2019_H2", "2020_H1", "2019_H2",
"2020_H1", "2019_H2", "2020_H1", "2019_H2", "2020_H1", "2019_H2",
"2020_H1"), subgroup = c("AS", "AS", "BL", "BL", "HI", "HI",
"Others", "Others", "WH", "WH"), fav = c(0.639136555607696, 0.83034379671151,
0.653710247349823, 0.822349570200573, 0.658051689860835, 0.812018489984592,
0.654872749844817, 0.819091796875, 0.624846248462485, 0.795588612464735
)), row.names = c(NA, -10L), class = c("tbl_df", "tbl", "data.frame"
))
情节代码
library(RColorBrewer)
library(scales)
library(ggplot2)
data %>%
ggplot( aes(x=survey_period, y=fav, group=subgroup, fill=subgroup, width=.7)) +
geom_col(colour="black",width=0.5,position=position_dodge(0.8)) +
ggtitle("Trended Favorability") +
theme(axis.line=element_line()) +
ylab("% Favorable") +
scale_y_continuous(labels = scales::percent_format(accuracy = 1)) + #
scale_fill_brewer(palette="PuBu") +
geom_text(aes(label=scales::percent(fav, accuracy=.1), size=3,color="white",fontface = "bold"))
我想知道此代码中需要更改哪些内容,以便每个条都有自己的标签。
答案 0 :(得分:1)
示例数据中缺少“fav_text”变量 - 所以我使用了“子组”:
library(RColorBrewer)
library(scales)
library(ggplot2)
data %>%
ggplot(aes(x=survey_period, y=fav, group=subgroup, fill=subgroup, width=.7)) +
geom_col(colour="black",width=0.5,position=position_dodge(0.8)) +
geom_text(aes(label=subgroup),
fontface = "bold",
vjust = -.5, # play with these to adjust position
hjust = .5, # play with these to adjust position
size = 3,
colour = "black",
position = position_dodge(0.8)) +
scale_y_continuous(labels = scales::percent_format(accuracy = 1)) + #
scale_fill_brewer(palette="PuBu") +
ggtitle("Trended Favorability") +
ylab("% Favorable") +
theme(axis.line=element_line())