ggplot2 - 从数值/整数数据中获取离散的X轴值

3
我有一些数据,想用ggplot2绘制图形,其中x轴是一个数字/整数值。当绘制图形时,我希望图表只显示数据集中存在的x值,而不添加x轴上的值(离散值)。下面是完全可重现的示例,演示了问题:即使提供的x轴值为1、3、25,所得到的图形在x轴上呈现出0、5、15、20、25。我尝试过对值进行转换,以及尝试使用离散刻度,但似乎都没有奏效。
编辑:虽然x轴上的值是数字/整数,但它们表示因素(即试验中的人数、发动机中的气缸数等),并不是连续值。
#Example
library(ggplot2)

row1 <- c(1, 1)
row2 <- c(3, 2)
row3 <- c(25, 10)

data <- data.frame()
data <- rbind(data, row1)
data <- rbind(data, row2)
data <- rbind(data, row3)
names(data) <- c("A", "B")

qplot(A, B, data = data, geom="line")


#Things Tried
qplot(factor(A), B, data = data, geom="line")    #geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?
qplot(as.factor(A), B, data = data, geom="line")    #geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?
qplot(character(A), B, data = data, geom="line")    #Error in character(A) : invalid 'length' argument
qplot(as.character(A), B, data = data, geom="line")    #geom_path: Each group consist of only one observation. Do you need to adjust the group aesthetic?
qplot(A, B, data = data, geom="line") + scale_x_discrete(breaks = data$A)    #Works, but values are too far apart
1个回答

1
这是你想要的吗?
#START WITH SAMPLE DATA SET AS PER QUESTION
library(ggplot2)
row1 <- c(1, 1)
row2 <- c(3, 2)
row3 <- c(25, 10)

data <- data.frame()
data <- rbind(data, row1)
data <- rbind(data, row2)
data <- rbind(data, row3)
names(data) <- c("A", "B")

#PRODUCE SOLUTION, MODIFY DATASET
df <- data
df$id <- 1:nrow(df)
df$Labels <- as.factor(df[,"A"])

#RENDER PLOT
ggplot(df,aes(id,B)) + 
    geom_path() + 
    scale_x_continuous(breaks=df$id,labels=df$Labels) +
    labs(x="A")

#EQUIVALENT QPLOT CODE:
qplot(id, B, data = df, geom="line") + 
    scale_x_continuous(breaks = df$id,labels=df$Labels) + 
    labs(x="A")

这会产生以下结果:

Result

对于价值而言,我个人认为你的数据呈现方式具有误导性,我倾向于以下方式进行呈现:
ggplot(df,aes(id,B)) + 
    geom_bar(stat="identity",aes(fill=Labels),color="black") + 
    scale_x_continuous(breaks=df$id,labels=paste("Trial:",df$Labels)) +
    labs(x="A",fill="Trial Number",title="Trial XYZ Results") +
    theme_bw() +
    theme(legend.position=c(0,1),legend.justification=c(0,1))

Result2


谢谢回复。这个解决方案很好用,但是有没有可能使用qplot函数来完成,而不是ggplot2函数?使用qplot可以创建更简洁的脚本,所以我尽量在能用它的时候坚持使用。另外,关于误导性表示:请看我在原始问题中的编辑。 - lolcodez
@lolcodez 我理解你的意思,但是数字暗示了它们之间的数值关系。我会将它们列为Trial 1、Trial 2、Trial 25等等,或者类似这样的名称。我已经在我的解决方案中添加了qplot代码。 - Nicholas Hamilton

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接