使用ggplot时获得离散值以连续标度提供

时间:2019-06-29 16:09:00

标签: r dataframe ggplot2 rjson

我有以下数据:

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

我在这里做什么错了?

1 个答案:

答案 0 :(得分:2)

我很幸运使用jsonlite的{​​{1}}:

fromJSON

enter image description here

编辑:

这是一个条形图。请注意,有两个“搜索”值,默认情况下堆叠在这里。

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

enter image description here

或者,如果您希望对它们进行排序,我喜欢ggplot(l,aes(x=features, y=value)) + geom_col(color = "white") + coord_flip() ;但请注意,它是按单个值而不是总值排序的;不确定要如何在“搜索”中处理两者:

forcats::fct_reorder

enter image description here