我正在嘗試將一些重復的 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'))
uj5u.com熱心網友回復:
您只能使用 向創建的物件添加一些東西ggplot。如果您不想ggplot在函式中進行呼叫,則不能使用 . 相反,你應該讓函式list在這個例子中回傳一個like:
library(ggplot2)
foo <- function(text) list(geom_point(),
labs(x = "", y = text))
ggplot(iris, aes( x = Species, y = Sepal.Length)) foo("bar")
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/409173.html
標籤:
上一篇:跨不同資料幀的條件匹配列
