简体   繁体   English

如何使用 r 中的 plot() 在 x 轴上创建带有有序字符变量的散点 plot?

[英]How do I create a scatter plot with ordered character variables on the x-axis using plot() in r?

My data kind of looks like this (except in a table imported from excel):我的数据看起来像这样(从 excel 导入的表除外):

x values: E, D, D, C, B, A, A x 值:E、D、D、C、B、A、A

y values: 0, 1, 2, 3, 5, 7, 8 y 值:0、1、2、3、5、7、8

I get 'Error in plot.window(...): need finite 'xlim' values'.我得到“plot.window(...) 中的错误:需要有限的 'xlim' 值”。 I tried to use plot(factor(x), y, type = "p") and am still getting a line instead of a point and a bar where there are two values for the same variable.我尝试使用plot(factor(x), y, type = "p")并且仍然得到一条线而不是一个点和一个条,其中同一变量有两个值。 Making it an ordered list by using factored<-factor(x), ordered = TRUE then plotting plot(factored, y, type = "p") also seems to have no effect and it defaults to alphabetical.通过使用factored<-factor(x), ordered = TRUE然后绘制plot(factored, y, type = "p")使其成为有序列表似乎也没有效果,并且默认为字母顺序。

Any help using the plot function would be great.使用 plot function 的任何帮助都会很棒。 Thank you!谢谢!

You need to factor your x variable, so that they are associated with a certain level, eg A -> 1, B-> 2 and so on.您需要考虑您的 x 变量,以便它们与某个级别相关联,例如 A -> 1、B-> 2 等等。

You plot using the numeric of the factor and label the x-axis with the levels:您使用因子的数字 plot 和 label 使用水平的 x 轴:

x = c("A","A","B","C","D","D","E")
y = c(0,1,2,3,5,7,8)

x=factor(x)

plot(as.numeric(x),y,xaxt="n")
axis(1,1:length(levels(x)),levels(x))

在此处输入图像描述

If you would like them to appear in the order it appears in x and not sorted alphabetically, for example:如果您希望它们按照它出现在 x 中的顺序出现,而不是按字母顺序排序,例如:

x = c("E","D","D","A","A","C","B")
y = c(8,5,7,0,1,3,2)
# or you specify it specifically, levels = c(....)
x=factor(x,levels=unique(x))

plot(as.numeric(x),y,xaxt="n")
axis(1,1:length(levels(x)),levels(x))

在此处输入图像描述

If you use package ggplot2 , the graph can be plotted even if x is not a factor, like in StupidWolf's answer .如果您使用 package ggplot2 ,即使x不是一个因素,也可以绘制图表,就像在StupidWolf's answer中一样。 Note that I create the data.frame with argument stringsAsFactors = FALSE .请注意,我使用参数stringsAsFactors = FALSE创建了 data.frame。

library(ggplot2)

df1 <- data.frame(x, y, stringsAsFactors = FALSE)

ggplot(df1, aes(x, y)) + geom_point() + theme_bw()

在此处输入图像描述

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM