如何绘制仪表图在R?
如何在R中绘制以下图?
How can i draw a following plot in R?
Red = 30
Yellow = 40
Green = 30
Needle at 52.
我很需要。
感谢
所以这里有一个完整的 ggplot
解。
So here's a fully ggplot
solution.
注意:从原始帖子中编辑,以在计量断点处添加数字指示符和标签,这似乎是OP在其注释中要求的。如果不需要指示符,请删除 annotate(...)
行。如果不需要标签,请删除 geom_text(...)
行。
Note: Edited from the original post to add numeric indicator and labels at the gauge breaks which seems to be what OP is asking for in their comment. If indicator is not needed, remove the annotate(...)
line. If labels are not needed, remove geom_text(...)
line.
gg.gauge <- function(pos,breaks=c(0,30,70,100)) {
require(ggplot2)
get.poly <- function(a,b,r1=0.5,r2=1.0) {
th.start <- pi*(1-a/100)
th.end <- pi*(1-b/100)
th <- seq(th.start,th.end,length=100)
x <- c(r1*cos(th),rev(r2*cos(th)))
y <- c(r1*sin(th),rev(r2*sin(th)))
return(data.frame(x,y))
}
ggplot()+
geom_polygon(data=get.poly(breaks[1],breaks[2]),aes(x,y),fill="red")+
geom_polygon(data=get.poly(breaks[2],breaks[3]),aes(x,y),fill="gold")+
geom_polygon(data=get.poly(breaks[3],breaks[4]),aes(x,y),fill="forestgreen")+
geom_polygon(data=get.poly(pos-1,pos+1,0.2),aes(x,y))+
geom_text(data=as.data.frame(breaks), size=5, fontface="bold", vjust=0,
aes(x=1.1*cos(pi*(1-breaks/100)),y=1.1*sin(pi*(1-breaks/100)),label=paste0(breaks,"%")))+
annotate("text",x=0,y=0,label=pos,vjust=0,size=8,fontface="bold")+
coord_fixed()+
theme_bw()+
theme(axis.text=element_blank(),
axis.title=element_blank(),
axis.ticks=element_blank(),
panel.grid=element_blank(),
panel.border=element_blank())
}
gg.gauge(52,breaks=c(0,35,70,100))
## multiple guages
library(gridExtra)
grid.newpage()
grid.draw(arrangeGrob(gg.gauge(10),gg.gauge(20),
gg.gauge(52),gg.gauge(90),ncol=2))
您可能需要调整 size = ...
和注释(...)
参数
geom_text(...)
实际尺寸。
You will likely need to tweak the size=...
parameter to geom_text(...)
and annotate(...)
depending on the actual size of your gauge.
IMO片段标签是一个很糟糕的主意:它们使图像混乱,并破坏图形的目的(如果指标处于安全 ,警告或危险领土)。
IMO the segment labels are a really bad idea: they clutter the image and defeat the purpose of the graphic (to indicate at a glance if the metric is in "safe", "warning", or "danger" territory).