gpt4 book ai didi

r - 如何在ggplot2中跨时间线绘制多行

转载 作者:行者123 更新时间:2023-12-03 23:07:35 24 4
gpt4 key购买 nike

我想显示特定时间段内工作编号的变化。理想情况下,我想使用 ggplot2 geom_dotplot然后根据它们所在月份的列为这些点着色。我还没有尝试过的一个想法:我是否需要使用 tidyr 将我的数据从宽格式重新格式化为长格式才能绘制此图?

示例数据

Month       Finance       Tech        Construction     Manufacturing
Jan 14,000 6,800 11,000 17,500
Feb 11,500 8,400 9,480 15,000
Mar 15,250 4,200 7,200 12,400
Apr 12,000 6,400 10,300 8,500

我当前的 r 代码尝试:我知道我需要通过行业类型的因素填充点颜色。也许我必须拥有长格式的数据才能这样做。
library(tidyverse)
g <- ggplot(dat, aes(x = Month)) +
geom_dotplot(stackgroups = TRUE, binwidth = 1000, binpositions = "all") +
theme_light()
g

这是我试图制作的情节的外观。理想情况下,我想将列值中的点分为每 1000 个点。那可能吗?

enter image description here

感谢您抽出时间帮助 R 新手并且正在学校学习。一如既往地受到赞赏,

最佳答案

我无法让 geom_dotplot 工作,y 轴总是出错。尝试类似的方法,首先旋转 long,我们每 1000 重复一次 Month+category,注意下面的这个解决方案四舍五入:

library(dplyr)
library(tidyr)
library(ggplot2)

test = pivot_longer(dat,-Month,names_to="category") %>%
group_by(Month,category) %>%
summarize(bins=ceiling(value/ 1000)) %>%
uncount(bins)

如果您希望四舍五入到最接近的 1000,请使用 floor()而不是 ceiling() .

然后情节:
test$Month = factor(test$Month,levels=dat[,1])

test %>% ggplot(aes(x=Month,y=1,col=category)) +
geom_point(position=position_stack()) +
scale_y_continuous(labels=scales::number_format(scale=1000))

enter image description here

关于r - 如何在ggplot2中跨时间线绘制多行,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/61413229/

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