我想從一個小數據框中產生一個餅圖。起初一切運作良好R - 奇怪的餅圖在ggplot中的行爲
library(ggplot2)
library(data.table)
c1 <- c(2,3)
c2 <- c("second","third")
c2 <- factor(c2, levels = c("first","second","third","fourth"))
c3 <- c(0.7,0.3)
cs <- data.frame(c1,c2,c3)
ct <- data.table(cs)
colx <- c("blue","red")
midpoint <- cumsum(ct$c3) - ct$c3/2
keycols = c("c1")
setkeyv(ct,keycols)
ct
c1 c2 c3
1: 2 second 0.7
2: 3 third 0.3
vysg <- ggplot(ct, aes(x=1,y=c3,fill=c2)) +
geom_bar(stat="identity",width=2) +
coord_polar(theta='y')+
theme(axis.ticks=element_blank(), axis.title=element_blank(),
axis.text.y = element_blank(), panel.grid = element_blank(),
axis.text.x = element_text(color=colx,size=15,hjust=0))+
scale_y_continuous(breaks = midpoint, labels = ct$c2) +
scale_fill_manual(values=colx) +
scale_x_continuous(limits=c(-1,2.5))
vysg
的問題開始,當我需要新行添加到數據幀(data.table)(零個結果第一和第四)
ctlab <- data.table(levels(c2))
nlabs <- ctlab[!V1%in%ct$c2]
nlabs[, V1 := factor(V1,levels=c("first","second","third","fourth"))]
nct <- data.frame(c1=c(1,4),c2=nlabs[,V1],c3=0)
ct <- rbind(ct,nct)
colx <- c("green","blue","red","brown")
ct$c2 <- factor(ct$c2,levels=c("first","second","third","fourth"))
ct$c4 <- as.character(ct$c2)
keycols = c("c1")
setkeyv(ct, keycols)
ct
c1 c2 c3 c4
1: 1 first 0.0 first
2: 2 second 0.7 second
3: 3 third 0.3 third
4: 4 fourth 0.0 fourth
data.table看起來不錯但圖表不是
midpoint <- cumsum(ct$c3) - ct$c3/2
vysg <- ggplot(ct, aes(x=1,y=c3,fill=c2)) +
geom_bar(stat="identity",width=2) +
coord_polar(theta='y') +
theme(axis.ticks=element_blank(), axis.title = element_blank(),
axis.text.y = element_blank(), panel.grid = element_blank(),
axis.text.x=element_text(color=colx,size=15,hjust=0)) +
scale_y_continuous(breaks = midpoint, labels = ct$c2) +
scale_fill_manual(values = colx) +
scale_x_continuous(limits = c(-1,2.5))
vysg
Warning message:
In `[[<-.factor`(`*tmp*`, n, value = "first/fourth") :
invalid factor level, NA generated
在標籤C4(串)更換C2後警告將不會出現,但圖表是不正常
midpoint <- cumsum(ct$c3) - ct$c3/2
vysg <- ggplot(ct, aes(x=1,y=c3,fill=c2)) +
geom_bar(stat="identity",width=2) +
coord_polar(theta = 'y') +
theme(axis.ticks=element_blank(), axis.title=element_blank(),
axis.text.y = element_blank(), panel.grid = element_blank(),
axis.text.x = element_text(color=colx,size=15,hjust=0)) +
scale_y_continuous(breaks = midpoint, labels = ct$c4) +
scale_fill_manual(values=colx) +
scale_x_continuous(limits=c(-1,2.5))
vysg
我想這個問題是隱藏在因子(C2)但無法找到如何修正它的方法。我明確地設置了兩個級別 - 舊數據框架和新數據框架。
只是不做一個餅圖。他們無可否認是有史以來最糟糕的圖表 –