我有一个数据框,我已经创建了一个柱形图。
区域IMD_Score1 East Devon 005A NA2 East Devon NA3 Devon 65.002364 SW 60 ….
试试这个:
library(ggplot2) #reproduce your dataset dataset <- data.frame( Area = c( "East Devon 005A", "East Devon", "Devon", "SW", "England", "IMD - Q3", "Eastern Locality" ), IMD_Score = c(NA, NA, 65.00236, 60.28269, 57.61097, 56.90886, 55.07258) ) # this a trick to keep rows with NA dataset$IMD_Score_to_plot <- if_else(is.na(dataset$IMD_Score), 0, dataset$IMD_Score) #create the label with No data available dataset$IMD_Score_label <- if_else(dataset$IMD_Score_to_plot == 0, "No data available", "") #plot (the clue is using two geom_text) latestChart = ggplot(dataset, aes_string(y = colnames(dataset[3]), x = colnames(dataset[1]))) + geom_col(fill = "#1f78b4") + coord_flip() + scale_x_discrete(dataset$Area) + labs(y = "xAxisTitle", title = "chartTitle") + theme_bw() + theme( panel.background = element_rect(fill = NA), panel.ontop = TRUE, panel.grid = element_line( colour = "grey", size = 0.25, linetype = "dashed" ), axis.title.y = element_blank() ) + geom_text( label = dataset$IMD_Score_to_plot, na.rm = FALSE, vjust = 0.5, hjust = 5 ) + geom_text(label = dataset$IMD_Score_label, vjust = 0.5, hjust = 0) latestChart
这是输出,我认为这是你想要的:
修改了你的代码。主要是改变加两个 geom_text 并删除 geom_label :
geom_text
geom_label
ggplot(dataset, aes(y = IMD_Score, x = Area)) + geom_col(fill="#1f78b4") + coord_flip() + scale_x_discrete() + labs(y=xAxisTitle, title=chartTitle) + geom_text(aes(label= round(IMD_Score, 2), y = IMD_Score - 3), col = "white", size = 4) + geom_text(aes(label = ifelse(is.na(IMD_Score), "No data available", ""), y = 3), col = "gray", hjust = 0) + theme_bw() + theme( panel.background = element_rect(fill = NA),panel.ontop = TRUE, panel.grid = element_line(colour = "grey", size=0.25, linetype = "dashed"), axis.title.y=element_blank() )