Warning: file_get_contents(/data/phpspider/zhask/data//catemap/8/file/3.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
R 在ggplot2中的堆叠条上方绘制总和值_R_Ggplot2_Bar Chart - Fatal编程技术网

R 在ggplot2中的堆叠条上方绘制总和值

R 在ggplot2中的堆叠条上方绘制总和值,r,ggplot2,bar-chart,R,Ggplot2,Bar Chart,如何在ggplot2中的堆叠条上方绘制每个类(在我的示例中:a=450,b=150,c=290,d=90)的总和值?以下是我的代码: #Data hp=read.csv(textConnection( "class,year,amount a,99,100 a,100,200 a,101,150 b,100,50 b,101,100 c,102,70 c,102,80 c,103,90 c,104,50 d,102,90")) hp$year=as.factor(hp$year) #Plott

如何在ggplot2中的堆叠条上方绘制每个类(在我的示例中:a=450,b=150,c=290,d=90)的总和值?以下是我的代码:

#Data
hp=read.csv(textConnection(
"class,year,amount
a,99,100
a,100,200
a,101,150
b,100,50
b,101,100
c,102,70
c,102,80
c,103,90
c,104,50
d,102,90"))
hp$year=as.factor(hp$year)

#Plotting
p=ggplot(data=hp)  
p+geom_bar(binwidth=0.5,stat="identity")+  
aes(x=reorder(class,-value,sum),y=value,label=value,fill=year)+
theme()

您可以通过创建每类总计的数据集来实现这一点(这可以通过多种方式实现,但我更喜欢):

您可以使用
vjust
参数使文本高于或低于条形图顶部,或者只需向
total
添加一些值即可:

p + geom_bar(binwidth = 0.5, stat = "identity") +  
    aes(x = reorder(class, -value, sum), y = value, label = value, fill = year) +
    theme() +
    geom_text(aes(class, total + 20, label = total, fill = NULL), data = totals)

您可以直接使用
ggplot2的内置摘要功能:

ggplot(hp, aes(reorder(class, -amount, sum), amount, fill = year)) +
  geom_col() +
  geom_text(
    aes(label = stat(y), group = class), 
    stat = 'summary', fun = sum, vjust = -1
  )

数据中有一列
金额
,但美学中有一列
-值
;这些不应该是一样的吗?的确如此。我试图编辑以修复该示例,但编辑被拒绝。。。
aes
调用应该是:
aes(x=reorder(class,-amount,sum),y=amount,label=amount,fill=year)+
我们如何才能在酒吧里为每年增加价值?@Mostafa请访问。我需要将fun.y=sum改为fun.y=sum,这样才能起作用。@Matt\B我猜你的意思是
fun=sum
p + geom_bar(binwidth = 0.5, stat = "identity") +  
    aes(x = reorder(class, -value, sum), y = value, label = value, fill = year) +
    theme() +
    geom_text(aes(class, total + 20, label = total, fill = NULL), data = totals)
ggplot(hp, aes(reorder(class, -amount, sum), amount, fill = year)) +
  geom_col() +
  geom_text(
    aes(label = stat(y), group = class), 
    stat = 'summary', fun = sum, vjust = -1
  )