【问题标题】:Getting Discrete Value supplied to continuous scale while using ggplot在使用 ggplot 时将离散值提供给连续比例
【发布时间】:2019-06-29 16:09:00
【问题描述】:

我有以下数据:

library(rjson)
library(ggplot2)


l='[{"a": "abc", "date": "20190506","model": "honda", "features":"weather", "value": 10},
{"a": "abc", "date": "20190506","model": "honda", "features":"bad", "value": 14},
{"a": "abc", "date": "20190506","model": "honda", "features":"failure", "value": 20},
{"a": "abc", "date": "20190506","model": "honda", "features":"not", "value": 1},
{"a": "abc", "date": "20190506","model": "honda", "features":"search", "value": 24},
{"a": "abc", "date": "20190506","model": "honda", "features":"esrs", "value": 2},
{"a": "abc", "date": "20190506","model": "honda", "features":"issue", "value": 1},
{"a": "abc", "date": "20190506","model": "honda", "features":"errors", "value": 30},

{"a": "abc", "date": "20190510","model": "ford", "features":"ice", "value": 12},
{"a": "xyz", "date": "20190509", "model": "honda", "features":"summer", "value":18},
{"a": "xyz", "date": "20190507", "model": "ford", "features":"hot", "value":14},

{"a": "abc", "date": "20190506","model": "ford", "features":"search", "value": 20},
{"a": "abc", "date": "20190510","model": "honda", "features":"400", "value": 18},
{"a": "xyz", "date": "20190509", "model": "ford", "features":"fail", "value":24},
{"a": "xyz", "date": "20190507", "model": "honda", "features":"200", "value":15}]'

当我以数据框的形式使用这些数据来绘制特征和值之间的条形图时,使用以下代码:

l = fromJSON(l)
df = data.frame(do.call(rbind, l))
ggplot(df, aes(y=features, x=value))

我收到以下错误:

Error: Discrete value supplied to continuous scale

我在这里做错了什么?

【问题讨论】:

  • 我没有运行你的代码,但我怀疑你所有的变量都是因素。如果这是真的,您应该在调用ggplot 之前将相应的转换为数字。您可以通过sapply(dat, class) 进行检查,其中 dat 是您的 data.frame 的名称。
  • 它显示每个变量的“列表”。
  • 我是 R 新手。你能帮忙改变他们的班级吗?
  • 看起来fromJSON 函数有一个简化参数。将此设置为 TRUE。然后,如果幸运的话,返回的对象将是一个字符向量列表。那么你的代码会导致我上面提到的因素情况。如果是,请使用dat$numVar <- as.numeric(dat$numVar) 将 dat 和 numVar 替换为适当的名称,以将每个因子变量转换为数字。

标签: r dataframe ggplot2 rjson


【解决方案1】:

我很幸运使用了jsonlitefromJSON

l = jsonlite::fromJSON(l) 
ggplot(l,aes(y=features, x=value)) + 
  geom_point()

编辑:

这是一个条形图。请注意,这里默认堆叠了两个“搜索”值。

ggplot(l,aes(x=features, y=value)) + 
  geom_col(color = "white") + 
  coord_flip()

或者如果你想让它们排序,我喜欢forcats::fct_reorder;但请注意,它是按单个值排序的,而不是按总值排序;不知道你想如何在“搜索”中处理这两个:

ggplot(l,aes(x=forcats::fct_reorder(features, value), y=value)) + 
  geom_col(color= "white") + coord_flip()

【讨论】:

  • 有没有办法得到条形图?
  • @user15051990。 SO上有很多(几乎30k)与ggplot2相关的问题。我怀疑一两个与条形图有关。
  • 我终于明白了。谢谢!
猜你喜欢
  • 2023-03-06
  • 2014-11-14
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2019-11-28
  • 1970-01-01
  • 2019-02-04
  • 2014-05-27
相关资源
最近更新 更多