使用ggplot2和log2_trans()进行log_2缩放的问题

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

我正在尝试在R中使用ggplot2绘制数据。数据点针对每个第2个第i个x值(4、8、16、32,...)出现。因此,我想按log_2缩放x轴,以使我的数据点均匀分布。当前,大多数数据点都聚集在左侧,这使我的绘图难以阅读(请参见第一个图像)。我使用以下命令获取此图像:

ggplot(summary, aes(x=xData, y=yData, colour=groups)) +
geom_errorbar(aes(ymin=yData-se, ymax=yData+se), width=2000, position=pd) +
geom_line(position=pd) +
geom_point(size=3, position=pd)

Plot without scaling

但是尝试用log2_trans缩放我的x轴会产生第二张图像,这不是我期望的,并且不会跟随我的数据。使用的代码:

ggplot(summary, aes(x=settings.numPoints, y=benchmark.costs.average, colour=solver.name)) +
geom_errorbar(aes(ymin=benchmark.costs.average-se, ymax=benchmark.costs.average+se), width=2000, position=pd) +
geom_line(position=pd) +
geom_point(size=3, position=pd) +
scale_x_continuous(trans = log2_trans(),
                 breaks = trans_breaks("log2", function(x) 2^x),
                 labels = trans_format("log2", math_format(2^.x)))

wrong log2 scaling

仅使用scale_x_continuous(trans = log2_trans())也无济于事。

编辑:

附上用于再现结果的数据:https://pastebin.com/N1W0z11x

编辑2:我已经使用函数pd <- position_dodge(1000)来避免错误条重叠,从而导致问题。删除position=pd语句可解决问题

r ggplot2 scale
2个回答
1
投票

这是格式化X轴的一种方法:

# Generate dummy data
x <- 2^seq(1, 10)
df <- data.frame(
  x = c(x, x, x),
  y = c(0.5*x, x, 1.5*x),
  z = rep(letters[seq_len(3)], each = length(x))
)

此图将如下所示:

ggplot(df, aes(x, y, colour = z)) +
  geom_point() +
  geom_line()

enter image description here

调整x轴将像这样:

ggplot(df, aes(x, y, colour = z)) +
  geom_point() +
  geom_line() +
  scale_x_continuous(
    trans = "log2",
    labels = scales::math_format(2^.x, format = log2)
  )

enter image description here

labels参数只是为了让您具有2^x格式的标签,您可以将其更改为所需的任何内容。


0
投票

我已经使用函数pd <- position_dodge(1000)来避免错误条的重叠,从而导致问题。根据新的缩放比例调整位置闪避的数量和误差线的大小可以解决此问题。

pd <- position_dodge(0.2) # move them .2 to the left and right

ggplot(summary, aes(x=settings.numPoints, y=benchmark.costs.average, colour=algorithm)) +
geom_errorbar(aes(ymin=benchmark.costs.average-se, ymax=benchmark.costs.average+se), width=0.4, position=pd) +
geom_line(position=pd) +
geom_point(size=3, position=pd) +
scale_x_continuous(
  trans = "log2",
  labels = scales::math_format(2^.x, format = log2)
)

enter image description here

添加scale_y_continuous(trans="log2")会得到我一直在寻找的结果:

enter image description here

© www.soinside.com 2019 - 2024. All rights reserved.