誰能幫我在 ggplot 中添加第二個 y 軸,或者將我制作的兩個單獨的 ggplot 組合起來?(附上R代碼)
資料:Dataframe = Deals1 包括三列(Year = Date,每年的交易數量 = N,每年的總交易價值 = total_tvalue)。
資料集包括 22 行(2000-2021 年),交易數量從 50-500 不等,交易價值從 100.000 到 800.000 不等
謝謝!
# Two seperate plots
plot1 = ggplot(Deals1, aes(x=Date, y=N)) geom_bar(stat = "identity")
plot2 = ggplot(Deals1, aes(x=Date, y=total_tvalue, group = 1)) geom_line(stat = "identity")
# Doesnt work
ggplot(Deals1, aes(x=Date))
geom_bar( aes(y=N), stat = "identity")
geom_line( aes(y=total_tvalue))
scale_y_continuous(
name = "Number of transactions",
sec_axis(name = "Transaction value"))
ggtitle("M&A Activity")
> dput(Deals1)
structure(list(Date = c("2000", "2001", "2002", "2003", "2004",
"2005", "2006", "2007", "2008", "2009", "2010", "2011", "2012",
"2013", "2014", "2015", "2016", "2017", "2018", "2019", "2020",
"2021"), N = c(428L, 337L, 222L, 243L, 220L, 228L, 230L, 215L,
146L, 143L, 131L, 94L, 121L, 128L, 154L, 161L, 156L, 139L, 159L,
121L, 74L, 95L), total_tvalue = c(796728L, 283487L, 124839L,
199670L, 276307L, 412632L, 379802L, 224635L, 188737L, 292432L,
141469L, 244239L, 126452L, 173573L, 404071L, 564486L, 400689L,
376499L, 477247L, 591219L, 262643L, 166189L)), row.names = c(NA,
-22L), class = "data.frame")
uj5u.com熱心網友回復:
ggplot 中的輔助軸只是繪制在繪圖一側的惰性注釋。它不會以任何方式影響實際繪圖面板上的內容。
在您的情況下,如果您在同一面板上同時繪制條形圖和線條,則看不到條形圖,因為線條比它們大 1,000 倍。
要在此處使用輔助軸,我們必須除以tvalue大約 1,000,使其與 的比例大致相同N。當然,這意味著任何閱讀我們圖表的人都會得到錯誤的數字,因為tvalue如果他們查看我們的 y 軸。這就是輔助軸的用武之地。我們指定輔助軸顯示的數字比“實際”大 1,000 倍。
此外,您的繪圖代碼還需要一些其他的調整。目前它根本沒有畫線,因為年份是字符格式而不是數字,所以你需要使用as.numeric(Date)或添加 agroup = 1到審美映射。其次geom_bar(stat = "identity")只是寫的很遠geom_col
library(ggplot2)
ggplot(Deals1, aes(as.numeric(Date)))
geom_col(aes(y = N), fill = "deepskyblue4", alpha = 0.8)
geom_line(aes(y = total_tvalue / 1500), color = "orangered3", size = 1)
scale_y_continuous(
name = "Number of transactions", breaks = 0:5 * 100,
sec.axis = sec_axis(~.x * 1500,
name = "Transaction value",
labels = function(x) {
paste0(scales::dollar(x/1000), "K")}))
ggtitle("M&A Activity")
theme_light(base_size = 16)

轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/474408.html
下一篇:如何將兩個單獨的直方圖合并為一個
