用标签替换X轴值并在ggplot中保持顺序

时间:2015-04-09 04:10:57

标签: r ggplot2

我有一个大数据框,部分内容如下:

data<-structure(list(b = c(-2.64, -2.184, -1.896, -1.874, -0.567, -0.454
), MLmisfit = c(-2.677, -1.92, -1.135, -0.512, -0.06, -0.048), 
    LzML = c(-1.145, -0.875, -0.562, -0.314, -0.074, -0.065), 
    HTML = c(-1.268, -0.935, -0.59, -0.305, -0.092, -0.08)), .Names = c("b", 
"MLmisfit", "LzML", "HTML"), row.names = c("Item12", "Item9", 
"Item3", "Item7", "Item4", "Item11"), class = "data.frame")

使用qplot语法,我可以创建下面的图表:

qplot(b,value,data=melt(data,id='b'),geom=c('line','point'),group=variable,col=variable)

enter image description here

数据集中大约有120个项目,因此手动标记不可行。我正在寻找一种方法来替换X轴上的点和数据集的rownames。我尝试使用scale_x_discrete,但它没有用。

2 个答案:

答案 0 :(得分:1)

以下是两个选项。我希望其中至少有一个适合你。

# Turn the rownames into a new data column
data$names = rownames(data)

选项1:使用geom_text

在图表上放置项目标签
ggplot(data=melt(data, id.var=c("b","names")), aes(b, value)) +
  geom_line(aes(group=variable, colour=variable)) + 
  geom_point(aes(colour=variable)) +
  scale_y_continuous(limits=c(-3.1,0.2)) +
  geom_text(data=data, aes(label=names, x=b), 
            y=-2.85, size=4, angle=-90, hjust=0)

选项2:将项目标签添加为轴标签,但使用geom_vline来掩盖不需要的垂直网格线

ggplot(data=melt(data, id.var=c("b","names")), aes(b, value)) +
  scale_y_continuous(limits=c(-3.1,0.2)) +
  scale_x_continuous(breaks=c(data$b,-1,-2), labels=c(data$names,-1,-2), 
                     minor_breaks=seq(-3,0,0.5)) +
  geom_vline(xintercept=data$b, colour=rgb(0,0,0,0.12)) +
  geom_line(aes(group=variable, colour=variable)) + 
  geom_point(aes(colour=variable)) 

enter image description here

答案 1 :(得分:1)

您要求不要根据“b”值打印x标签。然后试试这个

require(ggplot2)
require(reshape)
data["new_variable"] <- c(1:6)
data <- subset(data, select=-b)
qplot(new_variable,value,data=melt(data,id='new_variable'),geom=c('line','point'),group=variable,col=variable, xlab = "Items")+ scale_x_continuous(breaks=data$new_variable, labels=rownames(data)) + theme(axis.text.x = element_text(angle = 90, vjust = .5))

enter image description here