您如何专门订购 ggplot2 x 轴而不是字母顺序? [英] How do you specifically order ggplot2 x axis instead of alphabetical order?

查看:24
本文介绍了您如何专门订购 ggplot2 x 轴而不是字母顺序?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用 geom_tiles 函数使用 ggplot2 制作 heatmap这是我的代码如下:

I'm trying to make a heatmap using ggplot2 using the geom_tiles function here is my code below:

p<-ggplot(data,aes(Treatment,organisms))+geom_tile(aes(fill=S))+
  scale_fill_gradient(low = "black",high = "red") + 
  scale_x_discrete(expand = c(0, 0)) + 
  scale_y_discrete(expand = c(0, 0)) + 
  theme(legend.position = "right", 
    axis.ticks = element_blank(), 
    axis.text.x = element_text(size = base_size, angle = 90, hjust = 0, colour = "black"),
    axis.text.y = element_text(size = base_size, hjust = 1, colour = "black")).

data 是我的 data.csv 文件
我的 X 轴是治疗类型
我的 Y 轴是生物体的类型

data is my data.csv file
my X axis is types of Treatment
my Y axis is types of organisms

我对命令和编程不太熟悉,而且我在这方面相对较新.我只想能够指定 x 轴上标签的顺序.在这种情况下,我试图指定治疗"的顺序.默认情况下,它按字母顺序排列.我如何覆盖这个/保持数据的顺序与我的原始 csv 文件中的顺序相同?

I'm not too familiar with commands and programming and I'm relatively new at this. I just want to be able to specify the order of the labels on the x axis. In this case, I'm trying to specify the order of "Treatment". By default, it orders alphabetically. How do I override this/keep the data in the same order as in my original csv file?

我试过这个命令

scale_x_discrete(limits=c("Y","X","Z"))

其中 x、y 和 z 是我的治疗条件顺序.然而,它工作得不是很好,并且让我缺少加热盒.

where x, y and z are my treatment condition order. It however doesn't work very well, and give me missing heat boxes.

推荐答案

如果没有完整的、可重现的示例,要回答您的具体问题有点困难.但是这样的事情应该可以工作:

It is a little difficult to answer your specific question without a full, reproducible example. However something like this should work:

#Turn your 'treatment' column into a character vector
data$Treatment <- as.character(data$Treatment)
#Then turn it back into a factor with the levels in the correct order
data$Treatment <- factor(data$Treatment, levels=unique(data$Treatment))

在此示例中,因子的顺序将与 data.csv 文件中的顺序相同.

In this example, the order of the factor will be the same as in the data.csv file.

如果您喜欢不同的订单,可以手工订购:

If you prefer a different order, you can order them by hand:

data$Treatment <- factor(data$Treatment, levels=c("Y", "X", "Z"))

但是,如果您有很多关卡,这很危险:如果您弄错了其中任何一个,就会导致问题.

However this is dangerous if you have a lot of levels: if you get any of them wrong, that will cause problems.

这篇关于您如何专门订购 ggplot2 x 轴而不是字母顺序?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆