使用R中的分类向量绘制图

时间:2014-09-08 10:14:55

标签: r plot

我有三个向量如下:

x<-c(1:10)
type.1<-c('B','C','D','B','C','C','B','B','D','B')
type.2<-c('C','D','D','B','B','D','B','C','D','C')

我想用矢量x作为x轴和y中的其他矢量绘制这些矢量的一个图,其中每个数据矢量表示为直线,其中'B'部分显示为红色'C'部分是显示为蓝色,“D”部分显示为绿色。制作该图的点是比较不同类型的分布,因此这些线在y轴上彼此叠置的顺序并不重要。 我是R的新手,当我搜索我认为我应该使用ggplot但我找不到应该怎么做。 我很欣赏任何提示。

|
|red.blue.green.red.blue.blue.red.red.green.red       #straight line with different colors
|
|blue.green.green.red.red.green.red.blue.green.red    #straight line with different colors
|
|_________________________________________________
 1   2     3    4   5    6   7    8   9     10

1 个答案:

答案 0 :(得分:1)

需要重新格式化数据以便按照您的需要使用它,ggplot是一个不错的选择:

library(reshape2)
library(ggplot2)

# put data into a data frame for ggplot
dat <- data.frame(x=x, type.1=type.1, type.2=type.2)

# reshape the data from wide to long
dat_m <- melt(dat, id.vars = "x")

# start a ggplot, using the new "variable" column as the y values
# this will be what groups the values will automatically put new
# lines on top of each other
gg <- ggplot(dat_m, aes(x=x, y=variable, color=value))

# geom_segment draws line segments, and we just make the horizontal
# end the next x value and keep the vertical end the same
gg <- gg + geom_segment(aes(xend=x+1, yend=variable))

# these are the colors you wanted and this will map them to the factors
# in alpha order and names the legend "Data"
gg <- gg + scale_color_manual(values = c("red", "blue", "green"), name="Data")

# saving the world from grayscale gggplot backgrounds
gg <- gg + theme_bw()

# pick good labels. i just zero them out here
gg <- gg + labs(x="", y="")

# show the plot
print(gg)

enter image description here

检查?geom_segment以了解如何更改线宽和其他参数。