如何删除杂乱的x轴标签并按所需顺序排列?
# Data generation
dataPlot <- data.frame(iVal = sample(paste('i', 1:22, sep=''), 300, replace=TRUE),
facetVal = sample(LETTERS[1:3], 300, replace = TRUE),
value = runif(300, 0, 1))
# Original Facetted plot
ggplot(dataPlot, aes(iVal, value)) + geom_point() + facet_wrap(~facetVal)
# Data structure
str(dataPlot)
# 'data.frame': 300 obs. of 3 variables:
# $ iVal : Factor w/ 22 levels "i1","i10","i11",..: 10 20 1 21 16 7 11 18 ...
# $ value : num 0.2483 0.0298 0.5532 0.1117 0.0386 ...
# $ facetVal: Factor w/ 3 levels "A","B","C": 2 1 1 2 2 3 1 3 3 3 ...
# Data generation
dataPlot <- data.frame(iVal = sample(paste('i', 1:22, sep=''), 300, replace=TRUE),
facetVal = sample(LETTERS[1:3], 300, replace = TRUE),
value = runif(300, 0, 1), stringsAsFactors = FALSE)
# Original Facetted plot
ggplot(dataPlot, aes(iVal, value)) + geom_point() + facet_wrap(~facetVal)
在这种情况下如何设置手动中断(没有hand-picking the labels可以看到),其中标签不是数字(i1
... i22
)但这些点的顺序是相同的(1:22
)?我的意思是,而不是x轴上的所有22个标签,它们的子集,可能是10个具有相等间距和整齐轴的标签。
例如,像下面的x轴标签(但字符标签)
# Data generation
dataPlot <- data.frame(iVal = sample(1:22, 300, replace = TRUE),
facetVal = sample(LETTERS[1:3], 300, replace = TRUE),
value = runif(300, 0, 1), stringsAsFactors = FALSE)
# Original Facetted plot
ggplot(dataPlot, aes(iVal, value)) + geom_point() + facet_wrap(~facetVal)
答案 0 :(得分:1)
第一个建议 - 重新排序因子,并定义x轴抽动
# to reorder
dataPlot$iVal<- factor(dataPlot$iVal,
levels = unique(dataPlot$iVal[order(as.numeric(gsub("i","", dataPlot$iVal)))]),
ordered = TRUE)
ggplot(dataPlot, aes(iVal, value)) +
geom_point() + facet_wrap(~facetVal) +
scale_x_discrete(breaks=paste('i',seq(1,max(as.numeric(gsub("i","", dataPlot$iVal))),4),sep=""))
第二个建议 - 在情节标签上转换为数字和粘贴字符。
dataPlot$Val<- as.numeric(gsub("i","", dataPlot$iVal))
ggplot(dataPlot, aes(Val, value)) +
geom_point() + facet_wrap(~facetVal) +
scale_x_continuous(labels=function(x) paste0("i",x))