【问题标题】:Y scale on ggplot2 bar graph makes no senseggplot2条形图上的Y比例没有意义
【发布时间】:2017-08-28 10:59:10
【问题描述】:

我的条形图有一个奇怪的 Y 轴,似乎随机跳跃,从 -1.7% 到 -10.1%,-10.3%,然后到 -2%。你可以在下面看到它:

这是我的代码:

library(ggplot2)

healthd = read.csv("R/states.csv")

states = healthd[[1]]
insuredChange = healthd[[4]]
ggplot(data = healthd, aes(x = states, y = insuredChange)) +
geom_bar(stat="identity") +
theme(axis.text.x=element_text(angle = 90, hjust = 1))

这里发生了什么?我该如何解决?

另外,我怎样才能让 x 轴标签都在同一行右对齐?

【问题讨论】:

  • 检查 Y 轴值的类别。如果不是数字,则可能会发生此问题。
  • insuredChange 可能是一个字符或可能是一个因素,而不是numericclass(healtd$insuredChange)查看。
  • 请注意,轴中断不是随机的。它们是按字母顺序排列的。 “%”符号导致了问题。做healthd$insuredChange = as.numeric(as.character(gsub("%","",healthd$insuredChange)))。然后重新运行绘图代码。
  • 上面写着> class(healthd$insuredChange) [1] "NULL"
  • 如果没有完全可重现的数据版本,很难提供更多帮助。

标签: r csv graph ggplot2 charts


【解决方案1】:

首先 - 你提供的不是一个可重复的例子,没有人愿意注册访问你的数据来帮助你......

在您的代码中:

states = healthd[[1]]

insuredChange = healthd[[4]]

正在将列分配给全局环境 - 它们不会更改 data.frame 中值的名称。当您使用 ggplot 时,它会在您的 data.frame 中查找名称不存在的列 - 因此是 NULL 语句

 healthd$states = healthd[[1]]
 healthd$insuredChange = healthd[[4]]

将其更改为应该可以工作的东西 - 虽然我没有数据所以不完全确定。

现在应该会生成您想要的图形。

ggplot(healthd, aes(states, insuredChange)) +
       geom_bar(stat="identity") +
       theme(axis.text.x=element_text(angle = 90, hjust = 1))

【讨论】:

    猜你喜欢
    • 2018-12-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-01-26
    • 1970-01-01
    • 2016-03-27
    • 2018-11-20
    • 1970-01-01
    相关资源
    最近更新 更多