【问题标题】:Plotting with ggplot2: "Error: Discrete value supplied to continuous scale" on categorical y-axis用 ggplot2 绘图:在分类 y 轴上“错误:提供给连续刻度的离散值”
【发布时间】:2015-05-30 10:49:48
【问题描述】:

下面的绘图代码给出Error: Discrete value supplied to continuous scale

这段代码有什么问题?在我尝试更改比例之前它工作正常,所以错误就在那里......我试图从类似问题中找出解决方案,但无法解决。

这是我的数据的head

> dput(head(df))
structure(list(`10` = c(0, 0, 0, 0, 0, 0), `33.95` = c(0, 0, 
0, 0, 0, 0), `58.66` = c(0, 0, 0, 0, 0, 0), `84.42` = c(0, 0, 
0, 0, 0, 0), `110.21` = c(0, 0, 0, 0, 0, 0), `134.16` = c(0, 
0, 0, 0, 0, 0), `164.69` = c(0, 0, 0, 0, 0, 0), `199.1` = c(0, 
0, 0, 0, 0, 0), `234.35` = c(0, 0, 0, 0, 0, 0), `257.19` = c(0, 
0, 0, 0, 0, 0), `361.84` = c(0, 0, 0, 0, 0, 0), `432.74` = c(0, 
0, 0, 0, 0, 0), `506.34` = c(1, 0, 0, 0, 0, 0), `581.46` = c(0, 
0, 0, 0, 0, 0), `651.71` = c(0, 0, 0, 0, 0, 0), `732.59` = c(0, 
0, 0, 0, 0, 1), `817.56` = c(0, 0, 0, 1, 0, 0), `896.24` = c(0, 
0, 0, 0, 0, 0), `971.77` = c(0, 1, 1, 1, 0, 1), `1038.91` = c(0, 
0, 0, 0, 0, 0), MW = c(3.9, 6.4, 7.4, 8.1, 9, 9.4)), .Names = c("10", 
"33.95", "58.66", "84.42", "110.21", "134.16", "164.69", "199.1", 
"234.35", "257.19", "361.84", "432.74", "506.34", "581.46", "651.71", 
"732.59", "817.56", "896.24", "971.77", "1038.91", "MW"), row.names = c("Merc", 
"Peug", "Fera", "Fiat", "Opel", "Volv"
), class = "data.frame")

绘图代码:

## Plotting
meltDF = melt(df, id.vars = 'MW')
ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y = variable)) +
  scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
  scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))

这是添加比例之前的情节:

【问题讨论】:

  • 你的 y 值(变量)是因子,所以你不能使用scale_y_continuous
  • 任何快速解决方案如何将其更改为数字或所需的?谢谢!
  • 尝试了几个解决方案,但它不起作用或我做错了。

标签: r ggplot2 scale categorical-data r-factor


【解决方案1】:

如 cmets 中所述,factor 类型的变量不能有连续刻度。在定义 meltDF 变量之后,您可以将 factor 更改为 numeric,如下所示。

meltDF$variable=as.numeric(levels(meltDF$variable))[meltDF$variable]

然后,执行ggplot 命令

  ggplot(meltDF[meltDF$value == 1,]) + geom_point(aes(x = MW, y =   variable)) +
     scale_x_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200)) +
     scale_y_continuous(limits=c(0, 1200), breaks=c(0, 400, 800, 1200))

你就会得到你的图表。

希望对你有帮助

【讨论】:

    【解决方案2】:

    如果x 是数字,则添加scale_x_continuous();如果x 是字符/因子,则添加scale_x_discrete()。这可能会解决您的问题。

    【讨论】:

      【解决方案3】:

      在我的情况下,您需要将列(您认为该列是数字,但实际上不是)转换为numeric

      geom_segment(data=tmpp, 
         aes(x=start_pos, 
         y=lib.complexity, 
         xend=end_pos, 
         yend=lib.complexity)
      )
      # to 
      geom_segment(data=tmpp, 
         aes(x=as.numeric(start_pos), 
         y=as.numeric(lib.complexity), 
         xend=as.numeric(end_pos), 
         yend=as.numeric(lib.complexity))
      )
      

      【讨论】:

        猜你喜欢
        • 2016-07-26
        • 2014-07-06
        • 2019-01-04
        • 1970-01-01
        • 2021-11-12
        • 2015-01-08
        • 2023-01-31
        • 2015-09-26
        • 1970-01-01
        相关资源
        最近更新 更多