0

这个解决方案似乎已经死了。它是在 9 年零 10 个月前回答的,到那时它可以被中间的几个更新所取代。现在,举个例子,我想使用dputfrom this question(这是我的数据)。我当前创建绘图的代码版本如下所示:

ggplot(GoatMerged, aes(date, goat_pos, color = as.factor(GoatName))) +
geom_line() +
scale_x_datetime(date_breaks = '1 day') + 
labs(color = 'Goats', x='Time', y='Positions') +
theme(axis.text=element_text(size=6)) +
#theme(aspect.ratio=16/9) +
#coord_fixed(ratio=3/4) +
#theme(axis.title.y = element_text(size=40, vjust=2)) +
#theme(axis.title.x = element_text(size=40, vjust=-0.05)) +
theme_classic()
ggsave(filename="GoatPositionBosca.pdf", device = "pdf", width = 12, height = 7, units = "cm")

被注释掉的行表明我的其他尝试使情节起作用。现在,在 Windows 下的 R GUI 中,输出如下所示:

RGUI输出

然而, ggsave 使用后的输出device = "pdf"给出了该结果:

PDF输出

如我们所见,x 轴的数字标签重叠。尝试使用element_textlikesize或被vjustggsave 忽略的各种选项。

这就引出了一个问题:

device = "pdf"如何以不扭曲 x 轴数字标签的方式使用 ggsave ?


编辑

感谢@elielink 的评论,我可以进行一些更改,并且这样做还可以实现其他一些东西:

ggplot(GoatMerged, aes(date, goat_pos, color = as.factor(GoatName))) +
geom_line() +
scale_x_datetime(date_breaks = '1 day', guide = guide_axis(n.dodge = 2)) + 
labs(color = 'Goats', x='Time', y='Positions') +
theme_classic() +
theme(axis.text=element_text(size=6)) +
theme(legend.position = "bottom")
ggsave(filename="GoatPositionBosca.pdf", device = "pdf", width = 12, height = 9, units = "cm")

这给出了结果:

PDF2输出

在这里我们可以看到 PDF 切割了 x 轴编号标签的右侧,因此标签仍然失真。

4

1 回答 1

0

对于那些碰巧和我有同样问题的人,我想在这里给出我在处理 ggplot2 一段时间后得到的解决方案。创建图表的代码是:

ggplot(GoatMerged, aes(date, goat_pos, color = as.factor(GoatName), alpha=as.factor(EarStatus))) +
geom_line() +
geom_point() +
scale_alpha_manual(values = c(0.25, 1)) +
scale_x_datetime(date_breaks = '1 day', date_labels = "%d.%m.%Y") + #, guide = guide_axis(n.dodge = 2)) +
labs(color = 'Individual', alpha='some_category', x='Time points', y='Position') +
theme_bw() +
theme(legend.position = "bottom", legend.text=element_text(size = unit(11, "pt")), legend.title=element_text(size = unit(11, "pt"), face="bold"), legend.box = "vertical", legend.direction = "horizontal") +
theme(axis.title.y = element_text(size=unit(11, "pt"), face="bold", vjust=2)) +
theme(axis.title.x = element_text(size=unit(11, "pt"), face="bold", vjust=-2)) +
theme(axis.text=element_text(size=unit(8, "pt"))) +
theme(axis.text.x = element_text(colour = "black", face="bold")) +
theme(axis.text.y = element_text(colour = "black", face="bold")) +
theme(aspect.ratio=9/16) +
theme(plot.margin = unit(c(0,1.5,0,0.5), "cm"))
ggsave(filename="GoatPosition.pdf", device = "pdf", width = 17, height = 13, units = "cm", dpi = 600)

基于此,PDF 查看器中的图形如下所示:

PDF3输出

我们可以看到日期不重叠,最后一个日期完全在页面上并且没有被切断,并且所有标签都完全存在。事实证明,将 ggplot2 的纵横比与 ggsave 中以宽度和高度表示的比率一致设置对于不得到扭曲的图形至关重要。

于 2021-08-11T15:30:02.647 回答