我正在制作一份rmarkdown文档,其中我想使用ggplotly显示ggplot图表并在其下方包含图例。
为此,我使用下面解释的方法从ggplot图表中提取图例: ggplot separate legend and plot
我发现的问题是"边距"传说(或画布)是巨大的,传说显示远离我的主要情节。我想删除这些边距,以便绘图和图例彼此相邻显示。
我尝试了grid.newpage()
和---
title: "Stackq"
output: html_document
---
```{r setup, include=FALSE,echo=FALSE}
library(plotly)
library(ggplot2)
library(RColorBrewer)
library(grid)
library(cowplot)
df<-data.frame(x=runif(1000),y=runif(1000),z=rnorm(1000))
#function to extract the legend
g_legend<-function(a.gplot){
tmp <- ggplot_gtable(ggplot_build(a.gplot))
leg <- which(sapply(tmp$grobs, function(x) x$name) == "guide-box")
legend <- tmp$grobs[[leg]]
return(legend)}
```
```{r plotlyfig,echo=FALSE}
rf <- colorRampPalette(rev(brewer.pal(11,'Spectral')))
r <- rf(32)
p1 <-ggplot(df,aes(x=x,y=y,z=z))+ coord_fixed(ratio=1)+
stat_summary_hex(bins=100)+scale_fill_gradientn(colours=r)+ theme(legend.position="bottom")
p1leg<-g_legend(p1)
#using cowplot (the issue seems to be the same)
#p1leg<-cowplot::get_legend(p1)
p1<-p1+ theme(legend.position="none")
#print as ggplotly
ggplotly(p1)
```
```{r standalone_leg,echo=FALSE}
grid.draw(p1leg)
```
这两个函数,但是,我真的不明白在绘制grob时会发生什么。
有没有办法从图例中删除边距?
接下来,我将包含可重现的示例:
var query = (from con in db.Containers
join v in db.Vehicles on con.cont_vehicleid equals v.vehl_VehicleID
join cust in db.Custom_Captions on v.vehl_state equals cust.Capt_Code
where cust.Capt_Family == "vehl_state" && v.vehl_Deleted == null && con.cont_Deleted == null &&
v.vehl_ClearanceCompany == p.pusr_CompanyId && con.cont_Name.Contains(txtContNo.Text == null ? con.cont_Name : txtContNo.Text)
select new
{
cont_name = con.cont_Name,
vehl_Name = v.vehl_Name,
VehicleState = v.vehl_state,
vehl_drivername = v.vehl_drivername,
vehl_entrancedate = v.vehl_entrancedate,
vehl_customsdec = v.vehl_customsdec,
cont_rampid = v.vehl_rampid
}).ToList();
var query2 = (from con in db.Containers
join v in db.Vehicles on con.cont_vehicleid equals v.vehl_VehicleID
join cust in db.Custom_Captions on v.vehl_state equals cust.Capt_Code
where cust.Capt_Family == "vehl_state" && v.vehl_Deleted == null && con.cont_Deleted == null &&
v.vehl_ClearanceCompany == p.pusr_CompanyId && con.cont_customdec.Contains(txtCust.Text == null ? con.cont_customdec : txtCust.Text)
select new
{
cont_name = con.cont_Name,
vehl_Name = v.vehl_Name,
VehicleState = v.vehl_state,
vehl_drivername = v.vehl_drivername,
vehl_entrancedate = v.vehl_entrancedate,
vehl_customsdec = v.vehl_customsdec,
cont_rampid = v.vehl_rampid
}).ToList();
if (txtContNo.Text != "")
{
rptVehl.DataSource = query;
rptVehl.DataBind();
}
if (txtCust.Text != "")
{
rptVehl.DataSource = query2;
rptVehl.DataBind();
}