简体   繁体   中英

fill rectangles by a column in a data.frame with ggplot

I'm trying to create a ggplot with a line on 3 colored rectangles. I'd like to insert the proper fill color of each rectangle inside the database. Happens that the column is treated like a factor and the fill color is automatically set. This is my attempt:

library(ggplot2)

R<-rgb(185, 0, 51,alpha=1, maxColorValue=255)       
Y<-rgb(255, 255, 255,maxColorValue=255)     
G<-rgb(150, 191, 37,alpha=3,maxColorValue=255)      
R<-rgb(185, 0, 51,alpha=1, maxColorValue=255)       


sim<-seq(from=5000,to=14000,length.out=100) 
ut<-c(673,685,697,709,721,733,745,758,770,782,794,806,818,830,842,855,867,879,891,903,915,927,940,952,964,976,988,1000,1012,1025,1037,963,975,986,997,1008,1019,1030,1042,1053,1064,1075,1086,1097,1108,1120,1131,1142,1153,1164,1175,1186,1198,1209,1220,1231,1242,1253,1265,1276,1287,1298,1309,1320,1331,1176,1186,1195,1205,1215,1225,1235,1244,1254,1264,1274,1283,1293,1303,1313,1322,1332,1342,1352,1362,1371,1381,1391,1401,1410,1420,1430,1440,1449,1223,1231,1239,1247,1256,1264)

fasce<-data.frame(xmin=c(sim[1],7566,10517,13127),xmax=c(7566,10517,13127,13598),ymin=ut[1]*0.9,ymax=Inf,color=c(R,Y,G,R),stringsAsFactors =F)
data<-(data.frame(sim,ut))


ggplot() +geom_rect(data=fasce,aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax,fill=color))+
 geom_line(data=data, aes(x = sim, y = ut))+geom_hline(y=ut[1],xmin=sim[1]) 

I have also problem to display the hline correctly:I'd like make it start from ut[1]

在此处输入图片说明

You'll want to use scale_fill_identity to use the actual color names you give it. I removed alpha from rgb to get the color names as this was complicating things. If you want to change the transparency you can do it directly in ggplot2.

To add a horizontal line starting or ending at a specific point within the plot I use geom_segment instead of geom_hline .

The colors I used and put in your dataset fasce .

R = rgb(185, 0, 51, maxColorValue=255)       
Y = rgb(255, 255, 255, maxColorValue=255)     
G = rgb(150, 191, 37, maxColorValue=255)     

ggplot() +
    geom_rect(data=fasce, aes(xmin = xmin, xmax = xmax, ymin = ymin, ymax = ymax, fill=color)) +
    geom_line(data=data, aes(x = sim, y = ut)) +
    scale_fill_identity() +
    geom_segment(aes(x = min(sim), xend = Inf, y = ut[1], yend = ut[1]))

在此处输入图片说明

The scale_fill_identity function puts no legend by default. If you want the legend still, you could use something along the liens of scale_fill_identity(guide = "legend", breaks = fasce$color) .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM