在 ggplot 中的条形图上添加自定义标签
Add customized labels over bars in ggplot
我正在 ggplot2 中绘制一个简单的条形图,我需要在图中的每个条形图上显示与我正在使用的数据集无关的内容(数字或字符串..)。
例如使用以下指令:
ggplot(diamonds,aes(cut))+geom_bar()
我得到这张图:
我想在横条上显示数组的元素:
val<-c(10,20,30,40,50)
获得与其他图表类似的结果
我试过这样使用geom_text:
ggplot(diamonds,aes(cut))+geom_bar()+
geom_text(aes(label=val))
但我收到以下错误消息
Error: Aesthetics must be either length 1 or the same as the data (53940): label, x
问题是您正在使用 geom_bar
制作直方图,但没有指定 y
变量。为了应用this example,需要先总结cut
变量:
val<-c(10,20,30,40,50)
library(dplyr)
diamonds %>%
group_by(cut) %>%
tally() %>%
ggplot(., aes(x = cut, y = n)) +
geom_bar(stat = "identity") +
geom_text(aes(label = val), vjust = -0.5, position = position_dodge(0.9))
这给你:
我正在 ggplot2 中绘制一个简单的条形图,我需要在图中的每个条形图上显示与我正在使用的数据集无关的内容(数字或字符串..)。 例如使用以下指令:
ggplot(diamonds,aes(cut))+geom_bar()
我得到这张图:
我想在横条上显示数组的元素:
val<-c(10,20,30,40,50)
获得与其他图表类似的结果
我试过这样使用geom_text:
ggplot(diamonds,aes(cut))+geom_bar()+
geom_text(aes(label=val))
但我收到以下错误消息
Error: Aesthetics must be either length 1 or the same as the data (53940): label, x
问题是您正在使用 geom_bar
制作直方图,但没有指定 y
变量。为了应用this example,需要先总结cut
变量:
val<-c(10,20,30,40,50)
library(dplyr)
diamonds %>%
group_by(cut) %>%
tally() %>%
ggplot(., aes(x = cut, y = n)) +
geom_bar(stat = "identity") +
geom_text(aes(label = val), vjust = -0.5, position = position_dodge(0.9))
这给你: