ggplot2圆环图表与渐变的颜色

时间:2016-11-29 16:03:01

标签: r ggplot2 donut-chart

我想建立一个标准函数来在R中绘制圆环图following question对我有很大的帮助,但我不能用{{颜色'绘制情节。 3}}。

我的代码:

donut_chart <- function(data,variable1,variable2,col1="red",col2="yellow")
{
# Add addition columns to data, needed for donut plot.
data[,"fraction"] = data[,"variable2"]/ sum(data[,"variable2"])
data[,"ymax"] = cumsum(data[,"fraction"])
data[,"ymin"] = c(0, head(data[,"ymax"], n = -1))

# Palette

colfunc <- colorRampPalette(c(col1,col2))   

# Donut plot
ggplot(data, aes(fill = variable1, ymax = ymax, ymin = ymin, xmax = 4, xmin = 3)) +
     geom_rect(colour = "white", show_guide = FALSE) +
    coord_polar(theta = "y") + xlim(c(0, 4)) +
    scale_fill_manual(values=c(colfunc(levels(data[,"variable1"])))+ 
    theme_bw() + 
    theme(panel.grid=element_blank()) + 
    theme(axis.text=element_blank()) + 
    theme(axis.ticks=element_blank()) + 
    geom_text(aes(x = 3.5, y = ((ymin+ymax)/2), label = type),colour="white",size=6,fontface="bold") + 
    xlab("") + 
    ylab("")
    }

data.frame:

ad = data.frame(
  type = c("Poster", "Billboard", "Bus", "Digital"),
  n = c(529, 356, 59, 81)
)

输出代码:

donut_chart(ad,"type","n")

输出图仅以红色着色。

1 个答案:

答案 0 :(得分:2)

创建功能时要小心。 有时你把变量写成字符,有时候却是另一种方式。还要小心丢失括号。 这似乎有效:

gvDocs.HeaderStyle.CssClass;   // returns an empty string
gvDocs.HeaderRow.CssClass;   // returns an empty string
gvDocs.HeaderRow.Cells[i].CssClass;   // returns an empty string
gvDocs.HeaderRow.Cells[i].Attributes["class"];   // returns null
LinkButton lb = gvDocs.HeaderRow.Cells[i].Controls[0] as LinkButton;
lb.CssClass;   // returns an empty string
lb.Attributes["class"];   // returns null

哪个给了(我改变了文字的颜色,因为白色的白色很难读): enter image description here