我在ggplot2中创建堆积条形图。我有两个问题:
如何更改y轴和数据标签的比例,使其以1000为单位而不是1? 有什么方法可以让每个栏上显示总计数?例如,在第1栏上方以粗体显示94(千),在第2栏上方以122(千)表示。
library(ggplot2)
library(dplyr)
#Creating the dataset
my.data <- data.frame(dates = c("1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "1/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014", "2/1/2014"),
fruits=c("apple", "orange", "pear", "berries", "watermelon", "apple", "orange", "pear", "berries", "watermelon"),
count=c(20000, 30000, 40000, 2000, 2000, 30000, 40000, 50000, 1000, 1000))
#Creating a positon for the data labels
my.data <-
my.data %>%
group_by(dates) %>%
mutate(pos=cumsum(count)-0.5*count)
#Plotting the data
ggplot(data=my.data, aes(x=dates, y=count, fill=fruits))+
geom_bar(stat="identity")+
geom_text(data=subset(my.data, count>10000), aes(y=pos, label=count), size=4)
答案 0 :(得分:2)
这是创建情节的一种方式。首先,我们计算count
按dates
分组的总和。
sum_count <-
my.data %>%
group_by(dates) %>%
summarise(max_pos = sum(count))
此新数据框可用于绘制条形图顶部的总和。通过将值除以1000,可以将y轴更改为1000单位。
ggplot(data = my.data, aes(x = dates, y = count / 1000))+
geom_bar(stat = "identity", aes(fill = fruits))+
geom_text(data = subset(my.data, count > 10000),
aes(y = pos / 1000, label = count / 1000 ), size = 4) +
geom_text(data = sum_count,
aes(y = max_pos / 1000, label = max_pos / 1000), size = 4,
vjust = -0.5)