直方图颜色用R中的分类变量填充

时间:2022-05-30 14:56:58

I am trying to create a plot like this:

我想创建一个这样的情节:

qplot(carat, data = diamonds, geom = "histogram", fill = color)

However, instead of having a quantitative variable for the x-axis, I am using a categorical data. I am using a data frame like this:

但是,我没有使用x轴的定量变量,而是使用分类数据。我正在使用这样的数据框:

refBases=c("A","A","A","C","C","C","G","G","G","T","T","T")
altBases=c("C","G","T","A","G","T","A","C","T","A","C","G")
myDF$ref=refBases
myDF$alt=altBases
myDF$Freq=c(5,2,3,6,9,6,8,6,7,4,6,4)

So, basically, I would like my plot to look the same, except that the x-axis will be four bins from the ref column (A,C,G,T); the y-axis will be the Freq; and the color legend will be the four variables in the alt column (A,C,G,T). So, basically, there will be four ref bins on the x-axis, each divided into three parts along the y-axis, with the color legend indicating the alt value.

所以,基本上,我希望我的情节看起来一样,只是x轴将是ref列的四个区间(A,C,G,T); y轴将是Freq;并且颜色图例将是alt列中的四个变量(A,C,G,T)。因此,基本上,x轴上将有四个参考箱,每个参考箱沿y轴分为三个部分,颜色图例表示alt值。

I get something rather silly when I try what I expect:

当我尝试我期望的时候,我得到一些相当愚蠢的东西:

qplot(ref,Freq,data=myDF,fill=alt)

1 个解决方案

#1


1  

What you're describing doesn't sound like a histogram (which is a very specific plot for continuous random variables to estimate the kernel density); sounds like you just want a bar chart. I believe this is what you're looking for

您所描述的并不像直方图(这是连续随机变量估算核密度的非常具体的图);听起来你只想要一个条形图。我相信这就是你要找的东西

myDF <- data.frame(
    ref=c("A","A","A","C","C","C","G","G","G","T","T","T"),
    alt=c("C","G","T","A","G","T","A","C","T","A","C","G"),
    Freq=c(5,2,3,6,9,6,8,6,7,4,6,4)
)

library(ggplot2)
ggplot(myDF, aes(ref, Freq, fill=alt)) + 
    geom_bar(stat="identity", position="dodge")

直方图颜色用R中的分类变量填充

#1


1  

What you're describing doesn't sound like a histogram (which is a very specific plot for continuous random variables to estimate the kernel density); sounds like you just want a bar chart. I believe this is what you're looking for

您所描述的并不像直方图(这是连续随机变量估算核密度的非常具体的图);听起来你只想要一个条形图。我相信这就是你要找的东西

myDF <- data.frame(
    ref=c("A","A","A","C","C","C","G","G","G","T","T","T"),
    alt=c("C","G","T","A","G","T","A","C","T","A","C","G"),
    Freq=c(5,2,3,6,9,6,8,6,7,4,6,4)
)

library(ggplot2)
ggplot(myDF, aes(ref, Freq, fill=alt)) + 
    geom_bar(stat="identity", position="dodge")

直方图颜色用R中的分类变量填充