R语言 如何为ggplot2线图设置离散X轴而不丢失线条?

eqoofvh9  于 2023-03-20  发布在  其他
关注(0)|答案(1)|浏览(143)

我有一个 Dataframe ,如下所示:

corrtable <- data.frame(genes_included = c(rep(100,4),rep(1000,4),rep(5000,4),rep(10000,4)), percent_map_to_origin = runif(16), variation = rep(c("TCGA", "TCGA", "GTEx", "GTEx"),4), purity = rep(c("Included", "Excluded"),8))

我想在上面的ggplot 2中生成一个线图,例如,在0.99554361处有一条水平线。
我以前做过以下工作:

library(ggplot2)
ggplot(corr_table, aes(x = genes_included, y = percent_map_to_origin, color = variation, linetype = purity)) +
geom_line() +
geom_point() +
geom_hline(yintercept=0.99554361, color="darkslategray") +
labs(x = "Number of Genes Included", y = "% of Cell Lines That Correlate Highest to Origin Tissue") +
theme(text = element_text(face = "bold"), legend.text = element_text(size = 16), legend.title = element_text(size = 18), axis.title = element_text(size = 12), axis.text = element_text(size = 13)) +
scale_linetype_manual(values=c("dashed", "solid"))

这个方法确实有效,但是我想把x轴离散化,只列出100、1000、5000和10000,而不是一个连续的轴,我在其他地方看到过factor(),它确实有效,也确实把x轴离散化了,但是当我这样做的时候,我失去了连接点的线,这就是我添加因子的方法:

corrtable <- data.frame(genes_included = factor(c(rep(100,4),rep(1000,4),rep(5000,4),rep(10000,4))), percent_map_to_origin = runif(16), variation = rep(c("TCGA", "TCGA", "GTEx", "GTEx"),4), purity = rep(c("Included", "Excluded"),8))

我将感谢任何帮助我的x轴离散,但保持我的线之间的点。谢谢!

qij5mzcb

qij5mzcb1#

ggplot2可能会告诉您,在使用离散x比例时,您必须为线条设置group美学,即在您的情况下,在geom_line中执行group = interaction(variation, purity)

library(ggplot2)

ggplot(corr_table, aes(x = genes_included, y = percent_map_to_origin, color = variation, linetype = purity)) +
  geom_line(aes(group = interaction(variation, purity))) +
  geom_point() +
  geom_hline(yintercept = 0.99554361, color = "darkslategray") +
  labs(x = "Number of Genes Included", y = "% of Cell Lines That Correlate Highest to Origin Tissue") +
  theme(text = element_text(face = "bold"), legend.text = element_text(size = 16), legend.title = element_text(size = 18), axis.title = element_text(size = 12), axis.text = element_text(size = 13)) +
  scale_linetype_manual(values = c("dashed", "solid"))

相关问题