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

sca*_*der 4 r ggplot2 line-plot

我有以下数据框:

  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"))
Run Code Online (Sandbox Code Playgroud)

我想做的是使情节平滑。下面是我使用的代码:

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
Run Code Online (Sandbox Code Playgroud)

它产生以下图: 在此处输入图片说明

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

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

如何使它像这样平滑?但是具有预期的x轴顺序:

在此处输入图片说明

Jon*_*ing 6

The spline function seems to be thrown off by reading the data in order of appearance, whereas you are plotting it in order of the factor. It looks like this can be addressed by sorting the data before geom_xspline sees it:

lp_dat <- lp_dat[order(lp_dat$tc),]
Run Code Online (Sandbox Code Playgroud)

or:

library(dplyr)
lp_dat <- lp_dat %>% arrange(tc)
Run Code Online (Sandbox Code Playgroud)

then existing code:

在此处输入图片说明