R中的密度图 - 直方图 - ggplot

时间:2021-01-05 23:00:30

标签: r ggplot2 dplyr histogram density-plot

总结问题

我有以下数据:

<头>
收入水平 百分比
$0 - $1,000 10
$1,000 - $2,000 30
$2,000 - $5,000 60

我想创建一个具有密度标度的直方图。其中总数为 100%。 60% 超过了 3,000 的范围,所以我不能说它是 60%。我也知道范围是 [0 到 1000) [2000 到 3000)

我在谷歌上搜索了很多,并查看了我的笔记和书籍,但我找不到答案。我相信这很容易,但我是初学者。让我与您分享我尝试过的许多事情和谷歌,这是一路学习一些东西的机会。

描述您尝试过的内容

我想我可以用下面的代码轻松解决这个问题:

# I only added originally ggplot2 and dplyr.  As I was researching on Google, I tried a few solution that needed the string and data.table libraries.
library(ggplot2)
library(dplyr)
library(stringr)
library(data.table)


data <- data_frame(income = c(1000,2000,5000), percentage = c(10,30,40))

data %>% ggplot(aes(x = income)) +
  geom_histogram()

那不起作用,因为它正在计算值,所以我有 3 个高度 = 1 的条形,宽度也不正确。它没有从 0 到 1000、1000 到 2000 和 2000 到 5000。

经过几次搜索,我了解了 y=..density..。我把它放在我的 aes() 信息中。

data %>% ggplot(aes(x = income, y=..density..)) +
  geom_histogram()

y 轴不是 1 而是 0.0025(我不确定为什么)而且我不在那里。

然后我发现了 weight 并尝试了:

data %>% ggplot(aes(x = income, y=..density.., weight=percentage)) +
  geom_histogram()

我可能走在更好的轨道上,因为这是第一次柱子高度不同。

然后我尝试了 binwidth = c(1000, 2000, 5000) 因为图表具有不同的列宽。它不起作用。如果我尝试添加并从 0 开始,则会出现错误,因为有 4 个元素。

然后我了解了 cutbreak,但我不确定我是否理解。无论如何,现在代码看起来像那样。

library(ggplot2)
library(dplyr)
library(stringr)
library(data.table)

data <- data.frame(percentage = c(10,30,60))
data$income <- cut(data$percentage, c(0, 1000,2000,5000), right = FALSE)

data %>% ggplot(aes(x = income, y=..density.., weight=percentage)) +
  geom_histogram()

我现在有关于连续变量和离散变量的错误。

我在书中发现我也可以做馅饼。我尝试了以下方法来检查我的数据是否良好。

library(ggplot2)
library(dplyr)
library(stringr)
library(data.table)

data <- data_frame(income = c(1000,2000,5000), percentage = c(10,30,40))

# Create data for the graph.
x <- c(10,30,60)
labels <- c(1000,2000,5000)

pie(x,labels)

百分比看起来不错,但我没有创建我想要的那种图表。直方图而不是饼图。

我经常发现这个网站非常有帮助,所以也许有人知道答案。我刚刚创建了一个帐户,希望有人可以帮助我。

谢谢

1 个答案:

答案 0 :(得分:0)

也许您正在寻找条形图:

data %>% ggplot(aes(x = as.factor(income),y = percentage)) +
    geom_bar(stat = "identity") + labs(x = "Income")

enter image description here

或者如 stefan 所建议的那样,使用 geom_rec 可能是这样的:

data %>% 
  mutate(min = lag(income,1L, 0)) %>%
ggplot(aes(xmin = min, xmax = income, ymin = 0, ymax = percentage)) +
  geom_rect(color = "black") + labs(x = "Income", y = "Density")

enter image description here