簡體   English   中英

geom_col 中是否可以有可變寬度的條形?

[英]Is it possible to have variable width of bars in geom_col?

使用geom_col時可以選擇更改fillcol是否可以更改 geom_col 中條的寬度 - 就像下面的最后一行一樣?

dt <- data.table(diamonds) [ , .(total=.N, price = mean(price)), by = cut]; dt # data.table to work with

ggplot(dt) + geom_col(aes(x=cut, y=price, fill=total))   # we can do this
ggplot(dt) + geom_point(aes(x=cut, y=price, size=total)) # we can do this

ggplot(dt) + geom_col(aes(x=cut, y=price, size=total))   # this does something different
ggplot(dt) + geom_col(aes(x=cut, y=price, width=total))  # this does not work

或者有什么方法可以實現所需的 output - 我需要條形的寬度與total寬度成正比。
這是一個非常典型的情況:當你 plot 任何關於數據的事情時——你需要顯示這些數據的樣本大小

嘗試這個:

library(ggplot2)
library(data.table)

ggplot(dt) + 
  geom_col(aes(x=cut, y=price), width = dt$total/100000)

改變寬度參數的分母以改變列的絕對寬度。

代表 package (v0.3.0) 於 2020 年 6 月 13 日創建

我接受了上面的答案,基於它編寫了下面的代碼,它可以根據需要完成這項工作 - 通過在美學中移動width參數:

dt %>% ggplot(dt) + 
  geom_col( aes(x=cut, y=price, width = total/max(total)) )

這很好,因為您可以使用%>%在管道中調用它,因為您不需要在 function 中指定dt$

但是請注意,這會生成警告Warning: Ignoring unknown aesthetics: width (使用 ggplot2_2.2.1 版本),但它確實可以完成這項工作。

在此處輸入圖像描述

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM