【问题标题】:Changing angle of text in pie chart with respect to radius更改饼图中文本相对于半径的角度
【发布时间】:2020-08-11 12:27:54
【问题描述】:

我有一个关于在饼图中放置文本的问题。让我们有一个代码如下。

library(ggplot2)
pie_chart=function(vec){
  if (class(vec)=='numeric'){vec<-as.character(vec)
  vec<-print(paste('var',vec))
  }
  #creating data frame : variables and number of their occurrences
  df<-data.frame(table(vec))
  colnames(df)[1]<-'group'
  #creating bar plot first
  bp<- ggplot(df, aes(x="", y=Freq, fill=group))+
    geom_bar(width = 1, stat = "identity")
  blank_theme <- theme_minimal()+
    theme(
      axis.title.x = element_blank(),
      axis.title.y = element_blank(),
      panel.border = element_blank(),
      panel.grid=element_blank(),
      axis.ticks = element_blank(),
      plot.title=element_text(size=14, face="bold")
    )
  #adding polar coordinates to make a circle
  pie <- bp + coord_polar("y", start=0)
  pie + scale_fill_brewer("Characteristic") + blank_theme +
    theme(axis.text.x=element_blank())+
    geom_text(aes(y = rev(Freq)/2 + c(0, cumsum(rev(Freq))[-length(Freq)]),
                  label = print(paste0(rev(Freq),'(',percent(rev(Freq)/(sum(Freq))),')'))), size=5)
  
}



pie_chart(c(rep(1,40),rep(2,30),rep(3,60),rep(4,50)))

如您所见,它看起来像上面那样。对于每个饼图,文本都是水平的。有什么办法可以改变它?让我们在行中间有一个文本来限制一块馅饼。 IE。我想在下图中像线条一样放置文本。

你知道怎么做吗?

提前致谢!

【问题讨论】:

    标签: r ggplot2 visualization pie-chart


    【解决方案1】:

    您需要为饼图创建一个角度变量,就像使用位置变量一样,然后在 geom_text 中使用它来设置相对于圆中 365 度的角度。

    例如如果我们将其添加到来自https://www.r-graph-gallery.com/piechart-ggplot2.html 的示例中,它看起来像这样:

    library(ggplot2)
    library(dplyr)
    
    # Create Data
    data <- data.frame(
      group=LETTERS[1:5],
      value=c(13,7,9,21,2)
    )
    
    # Compute the position of labels
    data <- 
      data %>% 
      arrange(desc(group)) %>%
      mutate(prop = value / sum(data$value) *100) %>%
      mutate(ypos = cumsum(prop)- 0.5*prop) %>% 
      mutate(yang = 90-(ypos/100*365))  # Create an angle variable relative to the the text position
    
    # Basic piechart
    ggplot(data, aes(x="", y=prop, fill=group)) +
      geom_bar(stat="identity", width=1, color="white") +
      coord_polar("y", start=0) +
      theme_void() + 
      theme(legend.position="none") +
      geom_text(aes(y = ypos, label = group, angle = yang), color = "white", size=6) # add angle
    

    【讨论】:

      猜你喜欢
      • 2016-06-24
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-03-15
      • 2014-06-30
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多