gpt4 book ai didi

R ggplot 条形图,X 轴上有月份

转载 作者:行者123 更新时间:2023-12-04 01:52:35 25 4
gpt4 key购买 nike

我想要一个条形图,X 轴为月份,Y 轴为计数,二进制列 (status) 作为填充。这是包含错误、警告和我得到的情节的代码。如何获得正确的情节?

library(ggplot2)

# to read in date correctly
setClass("myDate")
setAs("character",
"myDate",
function(from) as.Date(from, format = "%Y-%m-%d"))

csvData <- "id,dt,status
1,2015-12-03,1
2,2015-12-05,1
3,2015-12-05,0
4,2015-11-24,1
5,2015-10-17,0
6,2015-12-18,0
7,2016-06-30,0
8,2016-05-21,1
9,2016-03-31,0
10,2015-12-31,0"

tmp <- read.csv(textConnection(csvData),
colClasses = c("integer", "myDate", "factor"))
tmp$mon <- as.Date(cut(tmp$dt, breaks = "month"))

# The plot must have this time frame on the X-axis
dtLimits <- as.Date(c("2015-01-01", "2016-08-01"))

# This does not work
# since x is a factor here and scale uses date
ggplot(data = tmp, aes(x = as.factor(mon))) +
geom_bar(aes(fill = status)) +
scale_x_date(date_breaks = "1 month",
labels = date_format("%y/%m"),
limits = dtLimits)
# Error: Invalid input: date_trans works with objects of class Date only

# wrong plot with warning message
ggplot(data = tmp, aes(x = mon)) +
geom_bar(aes(fill = status)) +
scale_x_date(date_breaks = "1 month",
labels = date_format("%y/%m"),
limits = dtLimits) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))
# Warning message:
# position_stack requires non-overlapping x intervals

最后一条语句产生的情节是这样的:

enter image description here

以下代码生成了正确的图表,但没有要求的限制并且缺少计数为 0 的月份。

ggplot(data = tmp, 
aes(x = as.factor(format(mon, format = "%y/%m")))) +
geom_bar(aes(fill = status)) +
theme(axis.text.x = element_text(angle = 90, hjust = 1))

enter image description here

最佳答案

当您处理日期时,x 轴以天为单位。条形宽度设置为数据分辨率的 90%,因此在这种情况下,如果您不设置 width 参数,则每个条形包含 0.9 天。将其更改为 30 以获得大约一个月的 bin。

ggplot(data = tmp, aes(x = mon)) + 
geom_bar(aes(fill = status), width = 30) +
scale_x_date(date_breaks = "1 month",
labels = date_format("%y/%m"),
limits = dtLimits) +
theme(axis.text.x = element_text(angle = 90, vjust = .5))

enter image description here

关于R ggplot 条形图,X 轴上有月份,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/38839923/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com