重新排列字符列值以进行绘图 [英] Reordering a character column values for plotting

查看:61
本文介绍了重新排列字符列值以进行绘图的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

以下是我拥有的数据帧的子集:

Following is a subset of the dataframe I have:

sample <- structure(list(MONTH_DAY = c("1_0", "1_1", "1_10", "1_11", "1_12", 
"1_13", "1_14", "1_15", "1_16", "1_17", "1_18", "1_19", "1_2", 
"1_20", "1_21", "1_22", "1_23", "1_3", "1_4", "1_5", "1_6", "1_7", 
"1_8", "1_9", "2_0", "2_1", "2_10", "2_11", "2_12", "2_13", "2_14", 
"2_15", "2_16", "2_17", "2_18", "2_19", "2_2", "2_20", "2_21", 
"2_22", "2_23", "2_3", "2_4", "2_5", "2_6", "2_7", "2_8", "2_9", 
"3_0", "3_1"), variable = structure(c(1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 
1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L, 1L), .Label = c("9", 
"10", "11", "12", "13"), class = "factor"), value = c(NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 
NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, NA, 51, 18
)), .Names = c("MONTH_DAY", "variable", "value"), row.names = c(NA, 
50L), class = "data.frame")

我正在使用 ggplot2 绘制图形,x轴的格式为MONTH_DAYOFMONTH,即1_13表示它的1月和13日同月,y轴表示计数(在数据框中为 value 列)。当我绘制数据时,使用以下命令:

I am plotting a graph using ggplot2 with x-axis being of the format MONTH_DAYOFMONTH i.e. 1_13 means it January and 13th of the same month, y axis indicating a count (which is value column in the dataframe). When I plot the data, using the command:

ggplot(sampleData, aes(x=MONTH_DAY, y=value, colour=variable, group=variable)) + `geom_line() + theme(axis.text.x=element_text(angle=90, size=4, hjust=-0.2, vjust=0.5)) + scale_colour_discrete("Months")`

x轴未排序,并显示x轴值为<$ c $的开头c> 1_0、1_1、1_10、1_11 ...而不是 1_0、1_1、1_2、1_3

the x-axis is not sorted and displays the starting with the x-axis values being 1_0, 1_1, 1_10, 1_11 ... instead of 1_0, 1_1, 1_2, 1_3.

如何对这些值进行排序,以使绘图显示数据是我想要的顺序?

How can I sort such values so that the plot shows the data is the order I would like to see?

推荐答案

我只是将其转换为日期并按如下方式绘制(注意,在给定所有值的数据栏中,两个都是 NA 所以我用 runif(50,max = 50) ...

I would just turn it into a date and plot it like this (N.B. in the data you gave all values bar two were NA so I made some values using runif(50 , max = 50)...

sampleData$MONTH_DAY <- as.Date( sampleData$MONTH_DAY , format = "%m_%d" )
ggplot(sampleData, aes(x=MONTH_DAY, y=value, colour=variable, group=variable)) + 
geom_line() +
theme(axis.text.x=element_text(angle=90, size=4, hjust=-0.2, vjust=0.5)) +        
scale_colour_discrete("Months")

< img src = https://i.stack.imgur.com/1Seb1.png alt =在此处输入图片描述>

这篇关于重新排列字符列值以进行绘图的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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