我想从已有的类创建直方图。我有这个数据集:
interval counts
0 - 8.50 2577
8.51 - 10.00 1199
10.01 - 12.00 1878
12.01 - 14.00 637
14.01 - 16.00 369
16.01 - 18.00 98
18.00 - 20.00 308
library(ggplot2)
plot_tab5_lohn <- ggplot(DS18, aes(x=interval)) + geom_histogram(stat="count")
return(plot_tab5_lohn)})
确实会生成此图表:
我希望计数在y轴上,间隔必须是不同的宽度。我怎么能这样做?
DS18$interval <- factor(DS18$interval, levels = DS18$interval)
output$DS32 <- renderPlot({
plot_tab5_lohn <- ggplot(DS18, aes(x=interval, y = counts)) +
geom_col() +
geom_point(color = "red") +
geom_line(aes(group = 1), color = "red")
return(plot_tab5_lohn)
})
我希望这些条纹与间隔本身一样宽。密度应该在Y轴上。那么面积的总和应该是1(100%)。 像这样link
答案 0 :(得分:2)
我认为你需要的不是直方图,而是一个条形图。在这里,我展示了如何使用geom_col
来创建一个条形图。请注意,在绘制数据之前,我使用factor
对每个类的条进行排序。
library(ggplot2)
# Order the bar
dt$interval <- factor(dt$interval, levels = dt$interval)
# Create the bar plot
ggplot(dt, aes(x=interval, y = counts)) + geom_col()
数据强>
dt <- read.table(text = "interval counts
'0 - 8.50' 2577
'8.51 - 10.00' 1199
'10.01 - 12.00' 1878
'12.01 - 14.00' 637
'14.01 - 16.00' 369
'16.01 - 18.00' 98
'18.00 - 20.00' 308",
header = TRUE, stringsAsFactors = FALSE)
答案 1 :(得分:1)
您可以使用stat = "identity"
并添加美学来获得所需的图表:
ggplot(DS18, aes(x=interval, y = counts)) +
geom_histogram(stat="identity")
给你这个:
答案 2 :(得分:1)
您可以提取边界,然后使用geom_rect
:
# Using dt from @www
library(tidyr)
dt2 <- separate(dt, interval, c('left', 'right'), sep = ' - ', convert = TRUE)
ggplot(dt2) +
geom_rect(aes(xmin = left, xmax = right, ymin = 0, ymax = counts),
col = 1) +
geom_line(aes(x = right + (left - right) / 2, y = counts),
col = 'red')
或者,您可以先将数据扩展为单个观察,这也可以让您轻松绘制密度:
library(dplyr)
library(tidyr)
dt3 <- dt %>%
group_by(interval) %>%
do(data.frame(interval = rep.int(.$interval, .$counts), stringsAsFactors = FALSE)) %>%
separate(interval, c('left', 'right'), sep = ' - ', convert = TRUE) %>%
mutate(value = right + (left - right) / 2)
breaks <- c(0, unique(dt3$right))
ggplot(dt3, aes(value)) +
geom_histogram(aes(y = ..density..), breaks = breaks, col = 1) +
geom_freqpoly(aes(y = ..density..), breaks = breaks, col = 'red')