更改数值的xlim导致错误ggplot R

时间:2016-04-03 13:41:11

标签: r ggplot2

我在R中使用ggplot生成了一个分组的条形图,其代码为

ggplot(mTogether, aes(x = USuniquNegR, y = value, fill = variable)) +
geom_bar(stat = "identity", position = "dodge") +
scale_fill_discrete(name = "Area", 
                    labels = c("Everywhere", "New York")) +
xlab("Reasons") +
ylab("Proportion of total complaints") +
coord_flip() +
ggtitle("Comparison between NY and all areas") 
使用以下代码

创建

mTogether

mTogether <- melt(together, id.vars = 'USuniquNegR')

数据框一起由

组成
      USperReasons      USperReasonsNY                 USuniquNegR
1    0.198343304187759   0.191304347826087                 Late Flight
2     0.35987114588127   0.321739130434783      Customer Service Issue
3   0.0667280257708237    0.11304347826087                Lost Luggage
4   0.0547630004601933 0.00869565217391304     Flight Booking Problems
5    0.109065807639208   0.121739130434783                  Can't Tell
6  0.00460193281178095                   0             Damaged Luggage
7   0.0846755637367694  0.0782608695652174            Cancelled Flight
8   0.0455591348366314  0.0521739130434783                  Bad Flight
9   0.0225494707777266  0.0347826086956522                   longlines
10  0.0538426138978371  0.0782608695652174 Flight Attendant Complaints

可以通过以下

生成
together<-data.frame(cbind(USperReasons,USperReasonsNY,USuniquNegR))

,其中

USperReasons <- c(0.19834,0.35987,.06672,0.05476,0.10906,.00460,.08467,0.04555,0.02254,0.05384)

USperReasonsNY <- c(0.191304348,0.321739130,0.113043478,0.008695652,0.121739130,0.000000000,0.078260870,0.05217391,0.034782609,0.078260870)

USuniquNegR <- c("Late Flight","Customer Service Issue","Lost Luggage","Flight Booking Problems","Can't Tell","Damaged Luggage","Cancelled Flight","Bad Flight","longlines","Flight Attendant Complaints")

问题是当我尝试使用

更改ggplot的xlim时
+ xlim(0, 1)

我似乎得到一个错误: 提供给连续比例的离散值 我无法理解为什么会发生这种情况,但我需要解决它,因为目前x轴从0开始并且包装非常高: image of ggplot output

2 个答案:

答案 0 :(得分:2)

问题在于你将cbind()同时放在一起,将数字转换为字符。解决这个问题,其余的应该自行解决。

together<-data.frame(USperReasons,USperReasonsNY,USuniquNegR)

答案 1 :(得分:1)

您需要从

中删除cbind
together<-data.frame(cbind(USperReasons,USperReasonsNY,USuniquNegR))

因为str(together)表示所有三列都是因素。

使用

together <- data.frame(USperReasons, USperReasonsNY, USuniquNegR)

情节看起来合情合理(无需使用ylimxlim)。

enter image description here

因此,错误不在ggplot2范围内,而是在数据准备中。 因此,请提供一个完整的工作示例,可以在下次提问时复制,粘贴和运行。谢谢。