针对 R 中的数字向量绘制字符向量 [英] Plot a character vector against a numeric vector in R
问题描述
我在 R 中有以下数据框:
I have the following data frame in R:
>AcceptData
Mean.Rank Sentence.Type
1 2.5 An+Sp+a
2 2.6 An+Nsp+a
3 2.1 An+Sp-a
4 3.1 An+Nsp-a
5 2.4 In+Sp+a
6 1.7 In+Nsp+a
7 3.1 In+Sp-a
8 3.0 In+Nsp-a
我想绘制的图,x 轴为 Sentence.Type 列,每个单元格的实际名称作为 x 轴上的一个点.我希望 y 轴以 0.5 的步长从 1 到 4
Which I want to plot, with the Sentence.Type column in the x axis, with the actual name of each cell as a point in the x axis. I want the y axis to go from 1 to 4 in steps of .5
到目前为止,我无法绘制此图,无论是使用 plot() 还是 hist().我不断收到不同类型的错误,主要是因为 data.frame 中字符列的性质.
So far I haven't been able to plot this, neither with plot() not with hist(). I keep getting different types of errors, mainly because of the nature of the character column in the data.frame.
我知道这对大多数人来说应该很容易,但我仍然对 R 有点菜鸟,并且在下班后我无法正确理解情节.任何帮助深表感谢.
I know this should be easy for most, but I'm sort of noob with R still and after hours I can't get the plot right. Any help is much appreciated.
我遇到的一些错误:
> hist(AcceptData$Sentence.Type,AcceptData$Mean.Rank)
Error in hist.default(AcceptData$Sentence.Type, AcceptData$Mean.Rank) :
'x' must be numeric
或者:(这不会产生错误,但绝对不是我想要的图表.它的所有 x 值都挤在 x 轴的左侧)
Or: (this doesn't give an error, but definitely not the graph I want. It has all the x values cramped to the left of the x axis)
plot(AcceptData$Sentence.Type,AcceptData$Mean.Rank,lty=5,lwd=2,xlim=c(1,16),ylim=c(1,4),xla b="Sentence Type",ylab="Mean Ranking",main="Mean Acceptability Ranking per Sentence")
推荐答案
默认的 plot
函数有一个方法可以让你在 x 轴上绘制因子,但是要使用它,你必须将您的文本数据转换为 factor
:
The default plot
function has a method that allows you to plot factors on the x-axis, but to use this, you have to convert your text data to a factor
:
这是一个例子:
x <- letters[1:5]
y <- runif(5, 0, 5)
plot(factor(x), y)
以及您的示例数据:
AcceptData <- read.table(text="
Mean.Rank Sentence.Type
1 2.5 An+Sp+a
2 2.6 An+Nsp+a
3 2.1 An+Sp-a
4 3.1 An+Nsp-a
5 2.4 In+Sp+a
6 1.7 In+Nsp+a
7 3.1 In+Sp-a
8 3.0 In+Nsp-a", stringsAsFactors=FALSE)
plot(Mean.Rank~factor(Sentence.Type), AcceptData, las=2,
xlab="", main="Mean Acceptability Ranking per Sentence")
这篇关于针对 R 中的数字向量绘制字符向量的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!