问题描述
我使用ggplot2
软件包制作了一个热图.我想使用annotate
函数在图的顶部添加一些文本.由于某些原因,文本被某些部分覆盖".如何显示完整标签?
I made a heatmap using ggplot2
package. I want to add some text on the top of the graph using the annotate
function. For some reason the text were "covered" by some portions. What can I do to show the full label?
示例数据如下:
data <- data.frame("group" = c("grp1", "grp2", "grp3", "grp4"), "pct" = runif(100, min = 0, max = 100))
data <- data %>%
group_by(group) %>%
mutate(id = row_number())
图形代码如下:
ggplot(data, aes(x=id, y=group, fill = pct)) +
geom_tile() +
theme_minimal() +
annotate("text", x = 3, y = 4.7, size = 3.2,label = "Morning") +
annotate("text", x = 7, y = 4.7, size = 3.2,label = "Afternoon") +
annotate("text", x = 12, y = 4.7, size= 3.2, label = "Evening") +
annotate("text", x = 17, y = 4.7, size = 3.2, label = "Night") +
theme(plot.margin = unit(c(0.3, 0.45, 0.3, 0.45), "cm"))
此图附在此处.您会看到早晨,下午,晚上和夜晚文本无法完全显示.我尝试使用plot.margin
命令添加边距,但是没有用.关于如何解决这个问题的任何想法?
The figure is attached here.You can see that the morning, afternoon, evening, and night text could not be displayed fully. I tried adding the margins using the plot.margin
command, but did not work. Any idea on how to fix that?
谢谢!
推荐答案
plot.margin
设置绘图外部的边距,而您需要在绘图内部留出更多空间. @Camille有一个正确的主意:您需要扩展y轴.幸运的是,这很简单:只需将expand
参数传递给scale_y_discrete
.
plot.margin
sets the margins around the outside of the plot, whereas you need to make more space inside the plot. @Camille has the right idea: you need to expand the y-axis. Luckily it's simple: just pass the expand
argument to scale_y_discrete
.
expand
只是在轴的侧面增加了额外的空间,因此数据是离散的(与使用ylim
不同)无关紧要.如果您想更详细地定义多余的空间(例如,仅在顶部添加空间),将expand_scale
传递给expand
参数(感谢@Camille!)可让您在每个单独4面.它还允许您添加绝对或相对的空间量.语法有点怪异,因此请检查?expand_scale
以查看参数名称:
expand
just adds extra space to the sides of the axis, so it doesn't matter that your data is discrete (unlike using ylim
). If you want to define the extra space in more detail (for example, to only add space to the top), passing expand_scale
to the expand
argument (thanks @Camille!) lets you define the extra space on each of the 4 sides individually. It also lets you add either an absolute or relative amount of space. The syntax is a bit weird, so check ?expand_scale
to see the argument names:
ggplot(data, aes(x=id, y=group, fill = pct)) +
geom_tile() +
theme_minimal() +
annotate("text", x = 3, y = 4.7, size = 3.2,label = "Morning") +
annotate("text", x = 7, y = 4.7, size = 3.2,label = "Afternoon") +
annotate("text", x = 12, y = 4.7, size= 3.2, label = "Evening") +
annotate("text", x = 17, y = 4.7, size = 3.2, label = "Night") +
scale_y_discrete(expand = expand_scale(mult = c(0, 0.3)))
这篇关于在图表上方显示文本(ggplot2)的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!