簡體   English   中英

在圓形條形圖的中心設置圖例 (ggplot2)

[英]Setting a legend in the center of a circular barplot (ggplot2)

我正在使用本教程創建圓形條形圖:https ://www.r-graph-gallery.com/295-basic-circular-barplot.html

我想在條形圖的中間創建一個圖例,即白色區域所在的位置。 但是,到目前為止,我只能在中間添加文本。 如果我想用顏色畫一個小立方體,它會自己環繞,我不知道它是如何使用坐標的(我試過 x = 0, y = 0 這給出了下面的結果,它們總是彎曲的)。

這是我添加的兩行:

geom_tile(aes(x = 1, y = 0, colour = "#EB5500"), width = 100, height = 100, inherit.aes = F) +
geom_text(x = 0, aes(y = -100, label = "test"), size = 4)

這樣完整的代碼現在看起來像這樣:

# Clear workspace 
rm(list = ls())

# Libraries
library(tidyverse)

# Create dataset
data <- data.frame(
  id=seq(1,60),
  individual=paste( "Mister ", seq(1,60), sep=""),
  value=sample( seq(10,100), 60, replace=T)
)

# Make the plot
p <- ggplot(data, aes(x=as.factor(id), y=value)) +       # Note that id is a factor. If x is numeric, there is some space between the first bar

  # This add the bars with a blue color
  geom_bar(stat="identity", fill=alpha("blue", 0.3)) +

  # Limits of the plot = very important. The negative value controls the size of the inner circle, the positive one is useful to add size over each bar
  ylim(-100,120) +

  # Custom the theme: no axis title and no cartesian grid
  theme_minimal() +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank(),
    plot.margin = unit(rep(-2,4), "cm")     # This remove unnecessary margin around plot
  ) +

  # This makes the coordinate polar instead of cartesian.
  coord_polar(start = 0) +
  geom_tile(aes(x = 1, y = 0, colour = "#EB5500"), width = 100, height = 100, inherit.aes = F) +
  geom_text(x = 0, aes(y = -100, label = "test"), size = 4)

p

但這給了我一個看起來像這樣的圖像: 在此處輸入圖片說明

看來ggplot會根據我添加的網格自動添加一個圖例。 該圖例需要位於中心,它應該是藍色條形圖而不是網格的圖例。 有沒有辦法做到這一點?

我對你的問題沒有真正理解的是傳說中應該是什么。 圖例的想法是它們解釋了映射( aes() ),因此您通常希望已經將其包含在數據中:

library(tidyverse)

data <- data.frame(
  id=seq(1,60),
  individual=paste( "Mister ", seq(1,60), sep=""),
  value=sample( seq(10,100), 60, replace=T),
  colour = "test1" # added to have something to map to
)

現在您可以將fill美學映射到新列。 要將圖例移動到中心,您必須將legend.position = c(0.5, 0.5)到您的theme

p <- ggplot(data, aes(x=as.factor(id), y=value, fill = colour)) +       # Note that id is a factor. If x is numeric, there is some space between the first bar
  geom_bar(stat="identity") +
  ylim(-100,120) +
  theme_minimal() +
  theme(
    axis.text = element_blank(),
    axis.title = element_blank(),
    panel.grid = element_blank(),
    legend.position = c(0.5, 0.5), # move legend to the center
    plot.margin = unit(rep(-2,4), "cm")     # This remove unnecessary margin around plot
  ) +
  coord_polar(start = 0)

p

我選擇test1來表明任何東西都可以進入數據。 要更改顏色,您必須定義手動(或其他)比例:

p +
  scale_fill_manual(values = alpha("blue", 0.3))

theme(legend.position = c(.5, .5))將圖例居中於情節。

暫無
暫無

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

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