【问题标题】:Plotting chart with table dataframe使用表格数据框绘制图表
【发布时间】:2018-06-20 10:43:10
【问题描述】:

有没有办法以水平方式而不是垂直方式绘制表格? 并绘制没有标签的表格?

我的代码:

Product <- c("Product1","Product2","Product3","Product4","Product5","Product6","Product7")
Value <- c(1000000,200002,599996,1399994,2199992,2999990,3799988)
df <- data.frame(Product,Value)
df$Product <- factor(df$Product, 
                     ordered = TRUE, 
                     levels = c("Product7","Product6","Product5","Product4","Product3",
                                "Product2","Product1"))

library(ggplot2)

p <- ggplot(df,aes(x=1,y=Value,fill=Product))+geom_bar(stat="identity")
p <- p + coord_polar(theta='y')+ 
  theme(axis.ticks=element_blank(),
        axis.text.y=element_blank(),
        axis.text.x=element_text(colour='black', size=12),
        axis.title=element_blank())
p <- p + scale_y_continuous(breaks=cumsum(df$Value) - df$Value / 2, 
                            labels= (paste(Product, 
                                           paste(round(((df$Value/sum(df$Value))*100),2),
                                                 "%"), 
                                           sep="\n")))
p <- p + guides(fill=FALSE)
p <- p + theme(panel.background = element_blank())

library(gridExtra)

t <- tableGrob(df)
grid.arrange(p,t)

我希望它是这样的

【问题讨论】:

    标签: r dataframe charts


    【解决方案1】:

    您可以将倒数第二行中的tableGrob(df) 替换为tableGrob(t(df)) 以在将数据帧传递给tableGrob() 之前对其进行转置。

    如果您喜欢每个单元格中没有灰色背景的更简洁的外观,请使用:

    tableGrob(t(df), theme = ttheme_minimal())
    

    我还建议不要将其命名为 t,因为它是基本包函数的名称。

    最后,如果你想为饼图分配更多的空间,你可以分配除c(1, 1)以外的高度比:

    tt <- tableGrob(t(df), theme = ttheme_minimal())
    grid.arrange(p, tt, heights = c(4, 1))
    

    旁注:p 的代码也可以简化为:

    ggplot(df, aes(x = 1, y = Value, fill = Product,
                   label = paste(Product, "\n",
                                 scales::percent(Value / sum(Value))))) + 
      geom_col() + 
      geom_text(aes(x = 1.6), # change this to shift label. smaller x = closer to pie center
                position = position_stack(vjust = 0.5)) +
      coord_polar(theta = 'y') +
      theme_void() +
      guides(fill = FALSE)
    

    解释:

    • geom_col() 等价于geom_bar(stat = "identity")
    • aes() 中设置饼图标签并添加geom_text() 层通常比自定义沿y 轴的中断更干净;
    • 使用来自scales 包的percent(),而不是手动将十进制值转换为百分比格式;
    • theme_void() 在一行中删除所有轴刻度、文本、标题、背景等。

    【讨论】:

    • 感谢您的帮助...!我尝试了几个小时来找出答案:'(
    猜你喜欢
    • 2021-11-24
    • 1970-01-01
    • 2020-02-17
    • 1970-01-01
    • 2015-08-27
    • 2016-11-15
    • 1970-01-01
    • 1970-01-01
    • 2017-11-23
    相关资源
    最近更新 更多