我正在尝试将一些重复的ggplot代码转换为函数。这样我就可以在需要时调用函数,或者可以在函数中写入整个ggplot码
我把代码放在重复的函数中
ggplot_common_function = function(text){
geom_bar(stat='identity',position=position_dodge(width=20),width=10)+theme_classic()+
theme(axis.line.y = element_blank(),axis.ticks = element_blank(),legend.position = "bottom",
axis.text.x = element_text(face = "bold", color = "black", size = 10, angle = 45, hjust = 1))+
labs(x="", y=text, fill="")+
theme(axis.title.y =element_text(size=8))+
scale_x_date(date_breaks ="1 month", date_labels ="%b-%Y")+
scale_y_continuous(labels = function(x) format(x, scientific = FALSE),expand = expansion(mult = c(0,.3)),breaks = integer_breaks())+
scale_fill_manual(values=c("#dfe022", "#288D55"))
}
调用ggplot内部的函数,但我遇到了一个错误(无法将ggproto对象添加到一起。你忘了将这个对象添加到ggplot对象中了吗?(
ggplotly(ggplot(aggregate(revenue~date+type,data=revenue_data(),FUN=sum),aes(x=date,y=revenue,fill=type,text=paste(revenue)))+
ggplot_common_function("INR (In Lakhs)"),expand = expansion(mult = c(0,.3)),tooltip = c("text"))%>%layout(legend = list(orientation = "h", x = 0.25, y = -0.2,font=list( family='Arial', size=10, color='black')),xaxis = x_labels,yaxis = y_labels)%>%config(displaylogo = FALSE,modeBarButtonsToRemove = list('sendDataToCloud', 'autoScale2d', 'resetScale2d', 'toggleSpikelines','hoverClosestCartesian', 'hoverCompareCartesian','zoom2d','pan2d','select2d','lasso2d','zoomIn2d','zoomOut2d'))
这是实际的整个ggplot代码
ggplotly(ggplot(aggregate(revenue~date+type,data=revenue_data(),FUN=sum),aes(x=date,y=revenue,fill=type,text=paste(revenue)))+
geom_bar(stat='identity',position=position_dodge(width=0.5),width=0.3)+theme_classic()+
theme(axis.line.y = element_blank(),axis.ticks = element_blank(),legend.position = "bottom",
axis.text.x = element_text(face = "bold", color = "black", size = 10, angle = 45, hjust = 1))+
labs(x="", y="INR (In Lakhs)", fill="")+
theme(axis.title.y =element_text(size=8))+
scale_y_continuous(labels = function(x) format(x, scientific = FALSE),expand = expansion(mult = c(0,.3)),breaks = integer_breaks())+
scale_fill_manual(values=c("#dfe022", "#288D55")),expand = expansion(mult = c(0,.3)),tooltip = c("text"))%>%layout(legend = list(orientation = "h", x = 0.25, y = -0.2,font=list( family='Arial', size=10, color='black')),xaxis = x_labels,yaxis = y_labels)%>%config(displaylogo = FALSE,modeBarButtonsToRemove = list('sendDataToCloud', 'autoScale2d', 'resetScale2d', 'toggleSpikelines','hoverClosestCartesian', 'hoverCompareCartesian','zoom2d','pan2d','select2d','lasso2d','zoomIn2d','zoomOut2d'))
您只能使用+
向ggplot
创建的对象添加内容。如果您不想在函数中使用ggplot
调用,则不能使用+
。相反,您应该让函数返回list
,如本例所示:
library(ggplot2)
foo <- function(text) list(geom_point(),
labs(x = "", y = text))
ggplot(iris, aes( x = Species, y = Sepal.Length)) + foo("bar")