gpt4 book ai didi

r - 无法更改 ggplot2 直方图上的颜色

转载 作者:行者123 更新时间:2023-12-02 03:38:36 25 4
gpt4 key购买 nike

我正在使用 5k 完成时间的数据集,看起来有点像这样:

"15:34"
"14:23"
"17:34"

等等,还有很多,不过都是这样的格式。我能够将它们全部转换为 POSIXct,并将它们存储在数据框中,以便更轻松地使用 ggplot2,但对于我来说,我无法让 ggplot 改变颜色。填充命令不起作用,图形只是保持灰色。

我尝试只引用我创建的 POSIXct 对象,但是 ggplot 抛出一个错误并告诉我它不能很好地与 POSIXct 配合使用。我能够显示直方图的唯一方法是将其存储在数据框中。

我当前使用的代码如下所示:

#make the data frame
df <- data.frame(
finish_times = times_list)


#set the limits on the x axis as datetime objects
lim <- as.POSIXct(strptime(c('2018-3-18 14:15', '2018-3-18 20:00'), format = "%Y-%m-%d %M:%S"))

#making the plot
ggplot(data = df, aes(x = finish_times)) +
geom_histogram(fill = 'red') + #this just doesn't work
stat_bin(bins = 30) +
scale_x_datetime(labels = date_format("%M:%S"),
breaks = date_breaks("1 min"),
limits = lim) +
labs(title = "2017 5k finishers",
x='Finish Times',
y= 'Counts')

我已经浏览了很多 ggplot 和 R 文档,我不确定我错过了什么,我感谢所有帮助,谢谢

最佳答案

stat_bin(bins = 30) 会覆盖您在 geom_histogram() 中设置的任何内容。一般来说,每个几何图形都有一个关联的默认统计数据,您可以使用两者之一来绘制对象,但是当您尝试同时使用两者时,最终可能会遇到问题。对此有几种解决方案。这是一个例子。

ggplot(diamonds, aes(x = carat)) + geom_histogram(fill = "red") + stat_bin(bins = 30)

生成一个灰色填充的图

enter image description here

ggplot(diamonds, aes(x = carat)) + geom_histogram(fill = "red", bins = 30)

生成一个红色填充的图

enter image description here

关于r - 无法更改 ggplot2 直方图上的颜色,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49354785/

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