作者热门文章
- html - 出于某种原因,IE8 对我的 Sass 文件中继承的 html5 CSS 不友好?
- JMeter 在响应断言中使用 span 标签的问题
- html - 在 :hover and :active? 上具有不同效果的 CSS 动画
- html - 相对于居中的 html 内容固定的 CSS 重复背景?
我正在尝试绘制一段时间内胎儿的体重。
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 ,创建一个变量刻度标签,使用格式来分隔天和周。
我提供了三种不同的方法。
下图是第二种方法。
我认为垂直刻度线也可以着色,这样如果您愿意,其中一些也可以消失。
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/
我是一名优秀的程序员,十分优秀!