无法按y值排序x轴

无法按y值排序x轴

本文介绍了ggplot2:无法按y值排序x轴的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我在ggplot2中用y值排序x轴时遇到问题:下面是代码

  #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,amount),y = amount,label = amount,fill = year)+
theme()

结果如下:


如何通过acbd对我的x轴进行排序,其数量按照450,290, 150,90.我该怎么办?

解决方案

您需要重新排列总和函数,否则它默认使用 mean 函数。然后,我在 amount 前面放置了一个 - 以使订单逆转。

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

I have problem in sorting x axis by y value in ggplot2: here is the code below

#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,amount),y=amount,label=amount,fill=year)+
theme()

Here is the result:

How do I sort my x axis by a c b d, which amount sorted by decreasing from 450, 290, 150, 90. What should I do?

解决方案

You need to give reorder the sum function, otherwise it defaults to using the mean function. Then, I put a - in front of amount to get the order reversed.

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

这篇关于ggplot2:无法按y值排序x轴的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-29 04:25