【问题标题】:How to change x axis (in order to be scaled) of a boxplot in R如何在 R 中更改箱线图的 x 轴(以便缩放)
【发布时间】:2018-11-14 11:29:33
【问题描述】:

我是 R 新手,在解决这个问题时遇到了一些麻烦。

我有以下表格/数据框:

我正在尝试生成这样的箱线图:

但是,我希望 x 轴根据标签 1000、2000、5000 等进行缩放。

所以,我希望 1000 和 2000 之间的距离与 50000 和 100000 之间的距离不同,因为确切的距离不一样。 是否可以在 R 中做到这一点?

谢谢大家,祝大家有个愉快的一天!

【问题讨论】:

  • 您能否使用dput(yourdf) 并提供示例数据而不是图片。对于那些愿意提供帮助的人来说,这会让事情变得更容易。干杯!

标签: r boxplot


【解决方案1】:

也许尝试将数据集转换为这种格式,即作为列中的整数,而不是标题?

# packages
library(ggplot2)
library(reshape2)

# data in ideal format
dt <- data.frame(x=rep(c(1,10,100), each=5),
                 y=runif(15))

# data that we have. Use reshape2::dcast to get data in to this format
dt$id <- rep(1:5, 3) 
dt_orig <- dcast(dt, id~x, value.var = "y")
dt_orig$id <- NULL
names(dt_orig) <- paste0("X", names(dt_orig))

# lets get back to dt, the ideal format :)
# melt puts it in (variable, value) form. Need to configure variable column
dt2 <- melt(dt_orig)

# firstly, remove X from the string
dt2$variable <- gsub("X", "", dt2$variable)

# almost there, can see we have a character, but need it to be an integer
class(dt2$variable)
dt2$variable <- as.integer(dt2$variable)

# boxplot with variable X axis
ggplot(dt2, aes(x=variable, y=value, group=variable)) + geom_boxplot() + theme_minimal()

重塑数据的基本方式:https://www.statmethods.net/management/reshape.html

【讨论】:

  • 仍然做不到:/ 试图将数据框转置为列,但没有工作。
  • 不用担心 :)。我已经修改了我的答案,以展示您如何重新工作和使用数据
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 2016-09-03
  • 1970-01-01
  • 2021-07-13
  • 2016-02-14
  • 1970-01-01
  • 2016-06-22
  • 1970-01-01
相关资源
最近更新 更多