如何在ggplot2中将标签写入图中

huangapple go评论71阅读模式
英文:

How to write the label into the plot in ggplot2

问题

我有一个带有y轴标签的绘图(在使用coord_flip之后)这是一个可重现的示例:

Names <- c("ExampleA","ExampleB","ExampleC","ExampleD", "ExampleE", "ExampleF","ExampleG", "ExampleH")
Counts <- c(4,3,2,1,-1,-2,-3,-4)
Type <- c("X","X","X","X", "Y","Y","Y","Y")
df <- data.frame(Names,Counts, Type)

ggplot(df, aes(x=reorder(Names,Counts), y=Counts, fill=Type))+
  geom_col()+
  coord_flip()+
  theme_minimal()

我希望标签被写在条形图旁边。也就是说,"ExampleA/B/C/D"等应该直接写在条形图旁边,而不是列在y轴上。

或者在可视化上:

我现在拥有的:

如何在ggplot2中将标签写入图中

我想要的:

如何在ggplot2中将标签写入图中(感谢Li等人,2021年 https://doi.org/10.3389/fimmu.2021.694801

我尝试过:

https://stackoverflow.com/questions/55406829/ggplot-put-axis-text-inside-plot

但没有成功。

这个:

geom_label(label=Names, parse=TRUE)

接近但不完全符合我的要求(对于真实数据,只有在我将每个名称手动键入矢量时才起作用,如果不是必要的话,我想避免这样做)。

我希望有类似于以下内容的选项:

geom_label(label=Names, position="inside")

scale_x_discrete(position = "inside")

但到目前为止,我还没有找到这样的解决方法。

英文:

I have a plot with the labels on the y axis (after using coord_flip)
Here is a reproducible example

Names &lt;- c(&quot;ExampleA&quot;,&quot;ExampleB&quot;,&quot;ExampleC&quot;,&quot;ExampleD&quot;, &quot;ExampleE&quot;, &quot;ExampleF&quot;,&quot;ExampleG&quot;, &quot;ExampleH&quot;)
Counts &lt;- c(4,3,2,1,-1,-2,-3,-4)
Type &lt;- c(&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;, &quot;Y&quot;,&quot;Y&quot;,&quot;Y&quot;,&quot;Y&quot;)
df &lt;-data.frame(Names,Counts, Type)

ggplot(df, aes(x=reorder(Names,Counts), y=Counts, fill=Type))+
  geom_col()+
  coord_flip()+
  theme_minimal()

I want the labels to be written next to the bars. Meaning that "ExampleA/B/C/D" etc. should be written right next to the bars and not listed on the y axis.
Or in visuals:
What I have

如何在ggplot2中将标签写入图中

What I want
如何在ggplot2中将标签写入图中
(Credit Li et al. 2021 https://doi.org/10.3389/fimmu.2021.694801)

I tried:
https://stackoverflow.com/questions/55406829/ggplot-put-axis-text-inside-plot
which didn't work.

This

geom_label(label=Names, parse=TRUE)

is close but not really what I want (and also for the real data only works when I type out every single name into a vector which I'd like to avoid if not nescessary).
I was hoping that there is something along the lines of

geom_label(label=Names, position=&quot;inside&quot;)

or

scale_x_discrete(position = &quot;inside&quot;)

would be possible, but thus far I could not find anything.

答案1

得分: 3

以下是您要翻译的部分:

已更新以匹配 OP 的所需输出和较长的名称。

已重新排列了原始 x 和 y 主题,以便我们可以避免 coord_flip 并按原样读取图表,而不是转置 x 和 y。

使用 hjustnudge_x 使文本定位更加健壮,前者对齐文本,后者提供文本和柱形图末端之间的填充。

至于长文本,这是通过在调用 scale_x_continuous 时创建图的两侧额外空间来管理的,并在调用 geom_text 时将文本大小设置为 3。另一种方法是编辑文本以包含换行符,但这在有许多条柱形图的情况下可能会有问题。

library(ggplot2)

Names <- c("ribonucleoside triphosphate biosynthetic process" ,"purine ribonucleoside triphosphate biosynthetic process" ,"ATP biosynthetic process" ,"proton motive force-driven ATP synthesis" ,"NADH dehydrogenase complex assembly" ,"mitochondrial respiratory chain complex I assembly" ,"innate immune response" ,"antigen processing and presentation of peptide antigen")
Counts <- c(4,3,2,1,-1,-2,-3,-4)
Type <- c("X","X","X","X", "Y","Y","Y","Y")

df <-data.frame(Names,Counts, Type)

ggplot(df, aes(Counts, reorder(Names,Counts), fill=Type))+
  geom_col()+
  geom_text(aes(label = Names, x = 0),
            size = 3,
            nudge_x = ifelse(Counts < 0, 0.05, -0.05),
            hjust = ifelse(Counts < 0, 0, 1)) +
  scale_x_continuous(expand = expansion(mult = c(0.75, 0.75)))+
  theme_minimal() +
  theme(axis.text.y = element_blank(),
        legend.position = "bottom")

如何在ggplot2中将标签写入图中

Created on 2023-06-26 with reprex v2.0.2

英文:

Updated to match OP's required output and long names.

Have rearranged x and y subjects from original so that we can avoid coord_flip and read the graph as is, rather than transpose x and y.

Made text positioning more robust using both hjust and nudge_x, the former aligns the text and the later provides the padding between the text and the end of the bar.

As for the long text this is managed by creating extra space either side of the plot using expansion in the call to scale_x_continuous and setting the text size to 3 in the call to geom_text. An alternative would be to edit the text to include a line break but this may be problematic where there are many bars.

library(ggplot2)

Names &lt;- c(&quot;ribonucleoside triphosphate biosynthetic process&quot; ,&quot;purine ribonucleoside triphosphate biosynthetic process&quot; ,&quot;ATP biosynthetic process&quot; ,&quot;proton motive force-driven ATP synthesis&quot; ,&quot;NADH dehydrogenase complex assembly&quot; ,&quot;mitochondrial respiratory chain complex I assembly&quot; ,&quot;innate immune response&quot; ,&quot;antigen processing and presentation of peptide antigen&quot;)
Counts &lt;- c(4,3,2,1,-1,-2,-3,-4)
Type &lt;- c(&quot;X&quot;,&quot;X&quot;,&quot;X&quot;,&quot;X&quot;, &quot;Y&quot;,&quot;Y&quot;,&quot;Y&quot;,&quot;Y&quot;)

df &lt;-data.frame(Names,Counts, Type)

ggplot(df, aes(Counts, reorder(Names,Counts), fill=Type))+
  geom_col()+
  geom_text(aes(label = Names, x = 0),
            size = 3,
            nudge_x = ifelse(Counts &lt; 0, 0.05, -0.05),
            hjust = ifelse(Counts &lt; 0, 0, 1)) +
  scale_x_continuous(expand = expansion(mult = c(0.75, 0.75)))+
  theme_minimal() +
  theme(axis.text.y = element_blank(),
        legend.position = &quot;bottom&quot;)

如何在ggplot2中将标签写入图中<!-- -->

<sup>Created on 2023-06-26 with reprex v2.0.2</sup>

答案2

得分: 0

以下是您要翻译的代码部分:

df <- data.frame(Names, Counts, Type) %>%
  arrange(desc(Type), desc(Names), Counts) %>%
  mutate(x2 = row_number(),
         y2 = ifelse(Type == 'X', -0.4, 0.4)) %>%
  arrange(Type, Names, Counts)

ggplot(df, aes(x = reorder(Names, Counts), y = Counts, fill = Type)) +
  geom_col() +
  coord_flip() +
  theme_minimal() + annotate(geom = 'text', y = df$y2, x = df$x2, label = df$Names) +
  theme(axis.text.y = element_blank())

请注意,我已经翻译了您提供的R代码部分。

英文:

Alternatively, you could create new variables x2 and y2 as below and use them in annotate function to generate the expected plot

df &lt;-data.frame(Names,Counts, Type) %&gt;% arrange(desc(Type), desc(Names), Counts) %&gt;% 
mutate(x2=row_number(),
       y2=ifelse(Type==&#39;X&#39;,-0.4,0.4)) %&gt;% 
  arrange(Type,Names,Counts)

ggplot(df, aes(x=reorder(Names,Counts), y=Counts, fill=Type))+
  geom_col()+
  coord_flip()+
  theme_minimal() + annotate(geom = &#39;text&#39;, y=df$y2, x=df$x2, label=df$Names) + 
  theme(axis.text.y = element_blank())

# output

      Names Counts Type x2   y2
1 ExampleA      4    X  8 -0.4
2 ExampleB      3    X  7 -0.4
3 ExampleC      2    X  6 -0.4
4 ExampleD      1    X  5 -0.4
5 ExampleE     -1    Y  4  0.4
6 ExampleF     -2    Y  3  0.4
7 ExampleG     -3    Y  2  0.4
8 ExampleH     -4    Y  1  0.4

如何在ggplot2中将标签写入图中

答案3

得分: 0

If the size of the Names is lengthy then we can decrease the size of the labels in annotate() as below:

ggplot(df, aes(x=reorder(Names,Counts), y=Counts, fill=Type))+
  geom_col()+
  coord_flip()+
  theme_minimal() + annotate(geom = 'text', y=df$y2, x=df$x2, label=df$Names, size=3) + 
  theme(axis.text.y = element_blank())

如何在ggplot2中将标签写入图中

英文:

If the size of the Names is lengthy then we can decrease the size of the labels in annotate() as below

ggplot(df, aes(x=reorder(Names,Counts), y=Counts, fill=Type))+
  geom_col()+
  coord_flip()+
  theme_minimal() + annotate(geom = &#39;text&#39;, y=df$y2, x=df$x2, label=df$Names, size=3) + 
  theme(axis.text.y = element_blank())

如何在ggplot2中将标签写入图中

huangapple
  • 本文由 发表于 2023年6月26日 20:49:23
  • 转载请务必保留本文链接:https://go.coder-hub.com/76556850.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定