有谁能帮我在or图中添加第二个y轴,或者将我所做的两个单独的g轴组合起来呢?(附r码)
data: Dataframe = Deals1包含三列(年份=日期,每年的事务数量= N,以及每年的总事务值= total_tvalue)。
数据集包括22行(2000-2021年),数字og事务从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")
发布于 2022-05-12 03:30:54
ggplot中的第二轴只是绘制在图的一侧的一个惰性注释。它不会以任何方式影响实际绘图面板上的内容。
在这种情况下,如果在同一面板上同时绘制条形图和线条,则无法看到条形图,因为这条线比它们大1000倍。
要在这里使用第二轴,我们必须将tvalue
除以大约1,000,这样它的规模与N
大致相同。当然,这意味着任何阅读我们图表的人如果看我们的y轴,就会得到错误的tvalue
数字。这就是第二轴进入的地方。我们指定,第二轴显示的数字比它们“真正”大1000倍。
此外,您的绘图代码还需要一些其他的调整。目前它根本没有画一条线,因为年份是字符格式而不是数字格式,所以您需要使用as.numeric(Date)
或向美学映射中添加一个group = 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://stackoverflow.com/questions/72213969
复制相似问题