gpt4 book ai didi

r - 如何将孕龄(以周.天为单位)放在ggplot中的x轴上

转载 作者:行者123 更新时间:2023-12-02 19:50:24 25 4
gpt4 key购买 nike

我正在尝试绘制一段时间内胎儿的体重。
Y 轴是以克为单位的胎儿体重
x 轴的格式需要如下所示:
7周3天==27.3
29 周 6 天 == 29.6
等等

我的数据(df)看起来像这样

weight age
2013 22.4
2302 25.6
2804 27.2
3011 29.1

我尝试过类似的方法...但不知道如何调整比例...

ggplot(df, aes(x = age, y = weight)) + 
geom_point() +
scale_x_continuous()

如果我得到年龄的实际数值(即 22.4 == 22weeks + 4/7days == 22.57),
是否可以用我想要的标签来标记对应的年龄值?
例如...

weight age.label age.value
2013 22.4 22.57
2302 25.6 25.86
2804 27.2 27.29
3011 29.1 29.14

当我这样称呼时:

df <- df %>% mutate(age.label = as.character(age.label))

ggplot(df, aes(x = age.value, y = weight)) +
geom_point() +
scale_x_continuous(label = "age.label")

我得到以下信息...

f(..., self = self) 中的错误:中断和标签的长度不同

非常感谢任何帮助

最佳答案

我借用了这个answer还有这个one ,创建一个变量刻度标签,使用格式来分隔天和周。

我提供了三种不同的方法。

  1. 仅在每天的点放置刻度,但不对其进行编号。
  2. 正确计算天和周,并通过将周设为粗体、将日期设为浅灰色来区分它们。
  3. 与 2 相同,但使用大小。这种方法效果不太好,因为它在标签和绘图之间造成了很大的差距。它被包含在内是为了完整性......并希望有人告诉我如何修复它。

下图是第二种方法。

enter image description here

我认为垂直刻度线也可以着色,这样如果您愿意,其中一些也可以消失。

library(ggplot2)
library(tidyverse)
df<-read.table(header=TRUE, text="weight age.label age.value

2013 22.4 22.57
2302 25.6 25.86
2804 27.2 27.29
3011 29.1 29.14")


#have ticks for every day using 1/7 distance tick marks
ggplot(df, aes(x = age.value, y = weight)) +
geom_point() +
scale_x_continuous(limits=c(22, 30),
minor_breaks = seq(from = 1, to = 33, by = 1/7),
breaks = 1:30)


#create a df of tick marks labels containing day number and week number
breaks_labels_df <- data.frame(breaks = seq(from = 1, to = 33, by = 1/7)) %>%
mutate(minors= rep(0:6, length.out = nrow(.)),
break_label = ifelse(minors == 0, breaks, minors))

#plot both day number and week number differentiating between them by the label formatting.
#remove the minor tick lines to reduce the busyness of the plot
ggplot(df, aes(x = age.value, y = weight)) +
geom_point() +
scale_x_continuous(limits=c(22, 30),
breaks = seq(from = 1, to = 33, by = 1/7),
labels = breaks_labels_df$break_label) +
theme(axis.text.x = element_text(color = c("grey60","grey60","black",rep("grey60",4)),
size = 8, angle = 0,
hjust = .5, vjust = .5,
face = c("plain","plain","bold",rep("plain",4))),
panel.grid.minor.x = element_blank()) +
labs(title = "Baby weight in relation to age", x = "Age in weeks and days", y = "weight in grams")



#Changing the font size places a large gap between the tick labels and the axis
ggplot(df, aes(x = age.value, y = weight)) +
geom_point() +
scale_x_continuous(limits=c(22, 30),
breaks = seq(from = 1, to = 33, by = 1/7),
labels = breaks_labels_df$break_label) +
theme(axis.text.x = element_text(vjust = 0, size = c(8,8,12,rep(8,4)),
margin = margin(t = 0), lineheight = 0))

关于r - 如何将孕龄(以周.天为单位)放在ggplot中的x轴上,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58300698/

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