你如何为ggplot中的条形图在x轴上做范围?
Posted
技术标签:
【中文标题】你如何为ggplot中的条形图在x轴上做范围?【英文标题】:How do you do ranges in the x-axis for a bar graph in ggplot? 【发布时间】:2021-10-18 21:52:45 【问题描述】:我正在创建一个条形图,并且需要能够在 x 轴上设置范围。
示例数据
Redear Sunfish 195
Redear Sunfish 210
Redear Sunfish 212
Redear Sunfish 215
Redear Sunfish 235
Redear Sunfish 242
我想了解这些鱼的尺寸范围(例如 50 - 100 毫米、100 - 150 毫米等)。
我现在的代码是
ggplot(data=Sunfish_Total_Length)+
geom_bar(mapping=aes(x=Total_Length_mm))
感谢您的帮助!
【问题讨论】:
【参考方案1】:如果我正确理解了这个问题,一种可能的解决方案是使用 cut()
函数,例如
library(tidyverse)
Sunfish_Total_Length <- tribble(
~"Species", ~"Total_Length_mm",
"Redear Sunfish", 195,
"Redear Sunfish", 210,
"Redear Sunfish", 212,
"Redear Sunfish", 215,
"Redear Sunfish", 235,
"Redear Sunfish", 242
)
Sunfish_Total_Length %>%
mutate(`Size Category (mm)` = cut(Total_Length_mm, breaks = seq(0, 250, 50))) %>%
ggplot(data = ., aes(x = `Size Category (mm)`)) +
geom_bar()
由reprex package (v2.0.0) 于 2021-08-17 创建
--
'Non-tidyverse' 样式代码:
# Non-pipe notation (i.e. no "%>%")
library(ggplot2)
Sunfish_Total_Length <- data.frame(
stringsAsFactors = FALSE,
Species = c(
"Redear Sunfish",
"Redear Sunfish",
"Redear Sunfish",
"Redear Sunfish",
"Redear Sunfish",
"Redear Sunfish"
),
Total_Length_mm = c(195, 210, 212, 215, 235, 242)
)
Sunfish_Total_Length
#> Species Total_Length_mm
#> 1 Redear Sunfish 195
#> 2 Redear Sunfish 210
#> 3 Redear Sunfish 212
#> 4 Redear Sunfish 215
#> 5 Redear Sunfish 235
#> 6 Redear Sunfish 242
Sunfish_Total_Length$`Size Category (mm)` <- cut(Sunfish_Total_Length$Total_Length_mm, breaks = seq(0, 250, 50))
Sunfish_Total_Length
#> Species Total_Length_mm Size Category (mm)
#> 1 Redear Sunfish 195 (150,200]
#> 2 Redear Sunfish 210 (200,250]
#> 3 Redear Sunfish 212 (200,250]
#> 4 Redear Sunfish 215 (200,250]
#> 5 Redear Sunfish 235 (200,250]
#> 6 Redear Sunfish 242 (200,250]
ggplot(data = Sunfish_Total_Length, aes(x = `Size Category (mm)`)) +
geom_bar()
由reprex package (v2.0.0) 于 2021-08-17 创建
【讨论】:
以上是关于你如何为ggplot中的条形图在x轴上做范围?的主要内容,如果未能解决你的问题,请参考以下文章