在 R ggplot 中,使用 'geom_rect' 可以生成下面的圖。現在,我有幾個問題:
- 有什么辦法可以簡化當前的代碼嗎?
- 如何在標簽中添加“數量”(目前僅包含“類別/子類別”)
- “填充顏色”很難看,尤其是“sub_category”(可能使用相同的顏色,只需更改“alpha”引數)
- 邊界不是很平滑(鋸齒狀邊框)
任何人都可以幫忙嗎?謝謝!
library(tidyverse)
test_data <- data.frame(category = c("retail","retail","retail","retail","retail","hotel"),
sub_category=c("retail_sub1","retail_sub2","retail_sub3","retail_sub4","retail_sub5","hotel"),
amount=c(51083.26,27454.13,22495.89,21195.05,16863.69,60210.6))
test_data1 <- test_data %>% mutate(ymax=cumsum(amount),
ymin=lag(cumsum(amount),default=0))
test_data1$y_category_position[test_data1$category=='retail'] <-
max(test_data1$ymax[test_data1$category=='retail'])/2
test_data1$y_category_position[test_data1$category=='hotel'] <-
max(test_data1$ymax[test_data1$category=='retail'])
max(test_data1$ymax[test_data1$category=='hotel'])/6 # tried may times, seems 6 for divisor is better
test_data1 %>% ggplot()
# for category bar and label
geom_rect(aes(xmin=3,xmax=6,ymin=ymin,ymax=ymax,fill=category))
geom_text(aes(x=4.5,y=y_category_position,label=category))
# for sub_category bar and label (exclude category 'hotel')
geom_rect(data= test_data1 %>% filter(sub_category !='hotel'),
aes(xmin=6,xmax=8,
ymin=ymin,ymax=ymax,fill=sub_category))
geom_text(data= test_data1 %>% filter(sub_category !='hotel'),
aes(x=7,y=(ymax ymin)/2,label=sub_category))
coord_polar(theta = 'y')
theme_minimal()

uj5u.com熱心網友回復:
以后,請在每個帖子中提出 1 個問題。
逐條回答您的問題。
- 這段代碼可以簡化嗎?
是的,您本質上有一個堆積條形圖,所以如果我們想要每個區域 1 個標簽,我們需要預先匯總資料,但不必費心預先計算累積和等。
library(tidyverse)
test_data <- data.frame(category = c("retail","retail","retail","retail","retail","hotel"),
sub_category=c("retail_sub1","retail_sub2","retail_sub3","retail_sub4","retail_sub5","hotel"),
amount=c(51083.26,27454.13,22495.89,21195.05,16863.69,60210.6))
barchart <- test_data %>%
# Reshape data
pivot_longer(-amount, names_to = "level", values_to = "name") %>%
# Filter out the hotel subcategory, leaving in the (super)category
filter(!(level == "sub_category" & name == "hotel")) %>%
# Sum over category level and names
group_by(level, name) %>%
summarise(amount = sum(amount), .groups = "keep") %>%
# Regular stacked bar chart code
ggplot(aes(x = level, y = amount))
geom_col(aes(fill = name), width = 1)
geom_text(
aes(label = paste0(name, "\n", amount), # <--- point 2
group = interaction(name, level)),
position = position_stack(vjust = 0.5),
)
barchart

隨后,添加coord_polar()將在圓環圖中制作條形圖。
barchart coord_polar(theta = "y")

由reprex 包(v2.0.1)于 2021 年 10 月 26 日創建
- 如何在標簽上添加“金額”?
您可以將其設定label = paste0(name, "\n", amount)為美學(請參閱代碼)。
- “填充顏色”很難看。
查看scale_fill_*()離散調色板的函式系列。
- 邊界不是很平滑。
That depends on the anti-aliasing for your graphics device. In RStudio you can set 'Tools > Global Options > General > Graphics > Backend > Select AGG' (or Cairo). For saving plots you could for example use ragg::agg_png().
轉載請註明出處,本文鏈接:https://www.uj5u.com/houduan/338242.html
