【问题标题】:Add significance asterisk to line graph in ggplot2在ggplot2中的折线图中添加显着性星号
【发布时间】:2020-05-08 13:36:20
【问题描述】:

我有以下数据,我用双线图绘制了这些数据。当重要性为“y”时,我想添加一个星号。

structure(list(Year = c(0, 1, 2, 3, 0, 1, 2, 3), school_type = c("Management Change", 
"Management Change", "Management Change", "Management Change", 
"Full Closure", "Full Closure", "Full Closure", "Full Closure"
), pct_change = c(3.7, 2, 0.8, -1.1, 9.2, 6.9, 5.4, 6.6), significance = c("y", 
"n", "n", "n", "y", "y", "y", "y")), row.names = c(NA, -8L), class = c("tbl_df", 
"tbl", "data.frame"))

我使用以下代码创建星号(在咨询 R ggplot2: add significance level to line plot 之后),但问题是我无法将这些星号向上移动以使它们脱离点,或者将字体更改为我想。我试过 nudge_y 但它没有用。

ggplot(fig4, aes(x=Year, y=pct_change, color=school_type, group=school_type)) +
  geom_line(size=1) +
  geom_point(size=3) +
  theme_bw(base_family = "Georgia") +
  geom_point(data = fig4[fig4$significance == "y", ], shape = "*", size=4.233, color="black")

每当我想在条形图中添加重要星号时,这都很容易。我输入:

ggplot(df, aes(label = ifelse(significance == "y", "*",""))

但是,由于某种原因,这对于折线图根本不起作用。为什么不呢?

【问题讨论】:

  • 请通过将您的数据包含为 data.frame 对象来使您的问题可重现,例如fig4
  • 对不起,我已经这样做了。

标签: r ggplot2


【解决方案1】:

1) 重要星号的定位

在主要数据的线或点上方获得显着性星号的简单方法是调整 aes 调用中的 y 值。查看答案。

如果您使用dplyr,您可以在生成绘图之前通过创建另一个变量(例如 sig_y 和 mutate)在数据集中对此进行预处理

2) 字体或字体系列:Georgia。

这有点复杂,我发现这些链接很有帮助:Changing fonts in ggplot2 和这个:https://github.com/wch/extrafont

使其他字体可供 R 访问:

library(extrafont) # package for accessing fonts on your computer assuming you are running windows
font_import() # imports all the fonts on your computer; may take several minutes
fonts <- fonttable() # tabulates the extracted fonts allows you to check what fonts you have and you can confirm that Georgia is in the mix

library(ggplot2)
library(tibble)
library(extrafont)

数据 (顺便说一句,这是为任何未来问题提供数据的有用方法,因为它使 SO 社区的成员可以轻松地重现您的问题。)

fig4 <- tibble(Year = c(0, 1, 2, 3, 0, 1, 2, 3),
               school_type = c("Management Change", "Management Change", "Management Change", "Management Change", 
                               "Full Closure", "Full Closure", "Full Closure", "Full Closure"), 
               pct_change = c(3.7, 2, 0.8, -1.1, 9.2, 6.9, 5.4, 6.6), 
               significance = c("y", "n", "n", "n", "y", "y", "y", "y"))

剧情脚本

loadfonts(device = "win") # to give access to non-ggplot fonts

ggplot(fig4, aes(x=Year, y=pct_change, color=school_type, group=school_type)) +
  geom_line(size=1) +
  geom_point(size=3) +
  theme_bw(base_family = "Georgia")+
  geom_point(data = fig4[fig4$significance == "y", ], aes(Year, pct_change + 0.25), shape = "*", size=4.233, color="black")

输出

【讨论】:

    猜你喜欢
    • 2018-03-06
    • 1970-01-01
    • 1970-01-01
    • 2020-11-08
    • 1970-01-01
    • 2020-06-19
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多