首页 > 解决方案 > 为什么我的直方图在 x 轴上没有负值?

问题描述

我正在绘制一个显示变量分布的直方图。绘制在 x 轴上的变量包含负值,但在直方图上,这些值不存在。

这是重现数据集样本的代码:

structure(list(`Cash Flowth EURLast avail. yr` = c(2.355, 14.677, 
-7.923, 53.66, 0, 91.336, 111.12, 11.945, -0.069, 4.42, 58.943, 
14.687, 11.17, 32.825, -1432.259, 2.852, 34.489, 198.515, 77.64, 
1.195, -53.123, -24.501, 18.244, 18.438, 16.668, 343.301, 0, 
-32.001, 41.009, -3.509, 71.679, 33.581, 638.27, 0, -1.262, -0.853, 
380.624, 26.533, 1.65, -30.007, -709.602, 1.877, -0.498, 3.77, 
-27.749, 15.599, -69.519, 6.331, 0.277, -150.365), general_status = c("Failed", 
"Active", "Failed", "Active", "Failed", "Active", "Active", "Active", 
"Failed", "Active", "Active", "Active", "Active", "Active", "Failed", 
"Active", "Active", "Active", "Active", "Failed", "Failed", "Active", 
"Active", "Active", "Failed", "Active", "Failed", "Failed", "Active", 
"Active", "Active", "Active", "Active", "Failed", "Active", "Failed", 
"Active", "Active", "Active", "Failed", "Failed", "Active", "Active", 
"Active", "Active", "Failed", "Active", "Active", "Failed", "Failed"
)), row.names = c(NA, -50L), class = c("tbl_df", "tbl", "data.frame"
))

这是我绘制直方图的代码:

df %>%
  filter(!is.na(`Cash Flowth EURLast avail. yr`)) %>%
  ggplot(aes(x = `Cash Flowth EURLast avail. yr`, fill = as.factor(general_status))) +
  geom_histogram(
      bins = nclass.Sturges(`Cash Flowth EURLast avail. yr`),colour = "black", position="identity")+
  scale_fill_manual(values = c("Active" = "springgreen4", "Failed" = "firebrick3"))+
  theme(legend.position="None", strip.background = element_rect(colour="black",
                                        fill="white"))+
  facet_grid(~general_status)

在此处输入图像描述

我该如何解决这个问题?知道min = -901535max = 8009206

标签: rggplot2histogram

解决方案


这可能没有资格作为答案,但很难解释为评论。

你的可变范围是

range(df$`Cash Flowth EURLast avail. yr`)
[1] -1432.259   638.270

当 x 轴范围太高时,您看不到实际存在的负值。您可能未指定xlim(-1500, 650)解决此问题。

另外,您的代码在我的计算机上不起作用。我换了bins = nclass.Sturges(Cash Flowth EURLast avail. yr)`

df %>%
  filter(!is.na(`Cash Flowth EURLast avail. yr`)) %>%
  ggplot(aes(x = `Cash Flowth EURLast avail. yr`, fill = as.factor(general_status))) +
  geom_histogram(
    bins = nclass.Sturges(df$`Cash Flowth EURLast avail. yr`), colour = "black", position="identity")+
  scale_fill_manual(values = c("Active" = "springgreen4", "Failed" = "firebrick3"))+
  theme(legend.position="None", strip.background = element_rect(colour="black",
                                                                fill="white"))+
  facet_grid(~general_status)

在此处输入图像描述


推荐阅读