ggplot:排列因子变量的混乱字符标签

问题描述 投票:0回答:1

如何删除杂乱的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 ...

enter image description here

# 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)

enter image description here

在这种情况下如何设置手动断点(没有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)

enter image description here

r ggplot2 axis-labels facet-wrap
1个回答
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))
© www.soinside.com 2019 - 2024. All rights reserved.