R中的诡计:奇怪的空第一列 [英] Barplots in R: Strange Empty 1st Column

查看:224
本文介绍了R中的诡计:奇怪的空第一列的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

下面的代码在R中创建一个Barplot。但是,第一列是空的。我不明白为什么...我的数据集中没有NA值。如何删除湾景列和Y轴之间的空间?

 #2 
barplot(xtabs(〜sample $ PoliceDistrict),
main =警区事件分布,
xlab =警区事件数目,
ylab =频率,
col = rainbow(nlevels(as.factor(sample $ PoliceDistrict))),
las = 2,
#cex.lab = 0.50这是用于x轴标签,
cex.names = 0.45

第一个空栏:

解决方案

您有一个空白的因子水平浮动,例如:

$ p $ x < - factor One,One,Two,Two,Two),levels = c(,One,Two))

$($)
#[1]OneTwo

barplot(table(x))
## EXTRA BAR PLOTTED

x< - droplevels(x)
#?droplevels
#函数'droplevels'用于从
#因子中删除未使用的等级,更常见的是来自数据框架中的因素。

levels(x)
#[1]OneTwo

barplot(table(x))
## FIXED


The following code creates a Barplot in R. However, the 1st column is empty. I don't understand why... There is no NA values in my data set. How can I remove the space between the "Bayview Column" and the Y-Axis?

# 2. Bar Plot for Police District
barplot(xtabs(~sample$PoliceDistrict), 
        main="Police District Distribution of Incidents", 
        xlab="Number of Incidents in Police District",
        ylab="Frequency",
        col=rainbow(nlevels(as.factor(sample$PoliceDistrict))),
        las=2,
        # cex.lab=0.50 This is for the x-axis Label,
        cex.names = 0.45
        )

Here is the resulting Barplot with the 1st empty column:

解决方案

You have a blank factor level floating about, e.g.:

x <- factor(c("One","One","Two","Two","Two"), levels=c("","One","Two") )

levels(x)
#[1] ""    "One" "Two"

barplot(table(x))
## EXTRA BAR PLOTTED

x <- droplevels(x)
# ?droplevels
# The function ‘droplevels’ is used to drop unused levels from a
# factor or, more commonly, from factors in a data frame.

levels(x)
#[1] "One" "Two"

barplot(table(x))
## FIXED

这篇关于R中的诡计:奇怪的空第一列的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆