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

标签 r ggplot2 line-plot ggalt

我有以下数据框:

  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

它产生以下图: enter image description here

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

我希望 x 轴的顺序为: c("NT", "IBD+PBS", "IBD+丝氨酸蛋白 enzyme 抑制剂") 因此它们被编码为一个因素。

怎样才能让它变得像这样光滑呢? 但按照预期的 x 轴顺序:

enter image description here

最佳答案

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

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

或者:

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

现有代码:

enter image description here

关于r - 如何绘制以 x 轴为因子的平滑线 (ggalt::xspline) 图,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57670231/

相关文章:

r - 从 R 调用 WinBUGS14

r - R 的 bigvis 包不适用于 R 版本 3.0.1 吗?

r - 逻辑回归双环 R

r - ggplot2条形图中的刻度标签

r - 为线条 ggplot2 分配颜色

形式为 0 <\alpha < 1 的 R 表达式

r - 使用两个不同长度的数据集在同一图形和比例中创建箱线图

r - 在不切断图形或丢失数据的情况下更改 ggplot 中的 y 轴限制

R 图添加了额外的不需要的线

r - 如何改变ggplot中的线宽?