【问题标题】:Add pie chart in a bar graph在条形图中添加饼图
【发布时间】:2020-11-03 11:33:52
【问题描述】:

我的目标是创建一个分类变量的条形图,然后在其中添加一个饼图,如附图所示。

我的数据和图片一样,如下:

#For bar grapgh  
chromosomes = c("1A", "1B", "1D", "2A", "2B", "2D", "3A", "3B", "3D", "4A","4B","4D","5A","5B","5D","6A","6B","6D","7A","7B","7D")
Frequency = c(668, 752, 213, 826, 948, 334, 625, 834, 264, 488, 391, 136, 745, 917, 234, 543, 848, 182, 901, 740, 241)
data_bar <- data.frame(chromosomes, Frequency)

#For pie chart
Genome = c("A","B","D")
Count = c(4796, 5430, 1604)
data_pie <- data.frame(Genome, Count)

如果有人能指导我或指导我找到答案,我将不胜感激

【问题讨论】:

    标签: r geom-bar geom-point


    【解决方案1】:

    这是ggplot2 解决方案:

    pie <- ggplot(data_pie, aes(x = 1, y = Count, fill = Genome)) + 
      geom_col(color = "black") + 
      scale_fill_manual(values = c("red2", "forestgreen", "dodgerblue3")) + 
      coord_polar(theta = "y") + 
      theme_void() + 
      theme(legend.position = "none")
    
     ggplot(data_bar) +
      geom_col(aes(chromosomes, Frequency, fill = substr(chromosomes, 2, 2)),
               color = "black", width = 0.5) +
      scale_fill_manual(values = c("red2", "forestgreen", "dodgerblue3")) +
       theme_classic() +
       theme(legend.position = "none") +
       annotation_custom(ggplotGrob(pie), xmin = "2B", xmax = "6A", ymin = 500)
    

    【讨论】:

    • 非常感谢,正是我要找的,1个简单的问题,当我将 ymin 从 500 更改为 700 时,饼图的大小变小了,你能解释一下为什么发生了,如果有办法设置大小,使其不会随位置改变?
    【解决方案2】:

    仅使用基本 R 函数,请参见下面的代码:

    ## Your data ---------------------------------
    #For bar grapgh  
    chromosomes = c("1A", "1B", "1D", "2A", "2B", "2D", "3A", "3B", "3D", "4A","4B","4D","5A","5B","5D","6A","6B","6D","7A","7B","7D")
    Frequency = c(668, 752, 213, 826, 948, 334, 625, 834, 264, 488, 391, 136, 745, 917, 234, 543, 848, 182, 901, 740, 241)
    
    #For pie chart
    Genome = c("A","B","D")
    Count = c(4796, 5430, 1604)
    
    ## One idea to start with --------------------
    
    plot.new()
    par(mfrow = c(2, 1), # set the layout, you might also consider layout() or split.screen() as suggested in ?par
        mar=c(4, 4, 1, 1), # this set up give enough space to see axis labels and titles
        oma=c(0, 0, 0, 0)) # remove outer margins
    pie(Count, labels = Genome)
    barplot(Frequency~chromosomes)
    

    输出:

    我认为调整par() 参数可以使它看起来更干净,但我对它们不是很熟悉。 还有一些包cowplotgridExtra 可以很好地与ggplot2 配合使用。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-06-04
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2023-03-08
      • 1970-01-01
      相关资源
      最近更新 更多