我有一些数据,我试图使用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
答案 0 :(得分: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")
产生以下结果:
对于它的价值,我个人认为上述数据的呈现具有误导性,并倾向于以下列方式表示:
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))