如何以 x 轴为因子绘制平滑线 (ggalt::xspline) 图

How to plot smoothed line (ggalt::xspline) plot with x-axis as factor

我有以下数据框:

  lp_dat <- structure(list(kmeans_cluster = c("1", "2", "3", "4", "1", "2", 
"3", "4", "1", "2", "3", "4"), tc = structure(c(2L, 2L, 2L, 2L, 
3L, 3L, 3L, 3L, 1L, 1L, 1L, 1L), .Label = c("NT", "IBD+PBS", 
"IBD+Serpin"), class = "factor"), n = c(924, 1389, 0, 652, 924, 
0, 0, 0, 110, 1389, 11851, 0)), row.names = c(NA, -12L), class = c("tbl_df", 
"tbl", "data.frame"))

我想做的是把剧情平滑一点。下面是我使用的代码:

lp <-   ggplot(lp_dat, aes(x = tc, y = n, group = 1)) +
  geom_point(color = "blue") +
  geom_line(linetype = "solid", size = 0.5, color = "blue") +
  ggalt::geom_xspline( size = 0.5, linetype = 'dashed') +
  facet_wrap(~kmeans_cluster, scales = "free_y") +
  theme_bw() +
  xlab("") +
  ylab("Count")

lp

它产生了以下情节:

注意到虚线是 ggalt::geom_xspline() 的预期平滑线。

我希望 x 轴的顺序为: c("NT", "IBD+PBS", "IBD+Serpin") 因此,它们被编码为一个因素。

我怎样才能让它变得像这样顺利? 但是使用预期的 x 轴顺序:

样条函数似乎通过按出现顺序读取数据而被抛出,而你是按因子顺序绘制它的。看起来这可以通过在 geom_xspline 看到它之前对数据进行排序来解决:

lp_dat <- lp_dat[order(lp_dat$tc),]

或:

library(dplyr)
lp_dat <- lp_dat %>% arrange(tc)

现有代码: