我需要在一个图表中绘制一个显示计数的柱状图和一个显示率的折线图,我可以分别做这两个,但当我把它们放在一起时,我的第一层(即geom_bar)的比例被第二层(即geom_line)重叠。

我可以将geom_line的轴向右移动吗?


当前回答

可以对变量使用facet_wrap(~ variable, ncol=)来创建一个新的比较。它们不在同一个轴上,但很相似。

其他回答

可以对变量使用facet_wrap(~ variable, ncol=)来创建一个新的比较。它们不在同一个轴上,但很相似。

从ggplot2 2.2.0开始,您可以添加如下的辅助轴(取自ggplot2 2.2.0公告):

ggplot(mpg, aes(displ, hwy)) + 
  geom_point() + 
  scale_y_continuous(
    "mpg (US)", 
    sec.axis = sec_axis(~ . * 1.20, name = "mpg (UK)")
  )

下面的文章帮助我将ggplot2生成的两个图合并到单行上:

一页上的多个图(ggplot2)由Cookbook for R

下面是代码在这种情况下的样子:

p1 <- 
  ggplot() + aes(mns)+ geom_histogram(aes(y=..density..), binwidth=0.01, colour="black", fill="white") + geom_vline(aes(xintercept=mean(mns, na.rm=T)), color="red", linetype="dashed", size=1) +  geom_density(alpha=.2)

p2 <- 
  ggplot() + aes(mns)+ geom_histogram( binwidth=0.01, colour="black", fill="white") + geom_vline(aes(xintercept=mean(mns, na.rm=T)), color="red", linetype="dashed", size=1)  

multiplot(p1,p2,cols=2)

我们当然可以用R函数图来建立一个双y轴的图。

# pseudo dataset
df <- data.frame(x = seq(1, 1000, 1), y1 = sample.int(100, 1000, replace=T), y2 = sample(50, 1000, replace = T))

# plot first plot 
with(df, plot(y1 ~ x, col = "red"))

# set new plot
par(new = T) 

# plot second plot, but without axis
with(df, plot(y2 ~ x, type = "l", xaxt = "n", yaxt = "n", xlab = "", ylab = ""))

# define y-axis and put y-labs
axis(4)
with(df, mtext("y2", side = 4))

以下内容结合了Dag Hjermann的基本数据和编程,改进了user4786271创建“转换函数”的策略,以优化组合图和数据轴,并响应了浸信会的提示,这样的函数可以在R中创建。

#Climatogram for Oslo (1961-1990)
climate <- tibble(
  Month = 1:12,
  Temp = c(-4,-4,0,5,11,15,16,15,11,6,1,-3),
  Precip = c(49,36,47,41,53,65,81,89,90,84,73,55))

#y1 identifies the position, relative to the y1 axis, 
#the locations of the minimum and maximum of the y2 graph.
#Usually this will be the min and max of y1.
#y1<-(c(max(climate$Precip), 0))
#y1<-(c(150, 55))
y1<-(c(max(climate$Precip), min(climate$Precip)))

#y2 is the Minimum and maximum of the secondary axis data.
y2<-(c(max(climate$Temp), min(climate$Temp)))

#axis combines y1 and y2 into a dataframe used for regressions.
axis<-cbind(y1,y2)
axis<-data.frame(axis)

#Regression of Temperature to Precipitation:
T2P<-lm(formula = y1 ~ y2, data = axis)
T2P_summary <- summary(lm(formula = y1 ~ y2, data = axis))
T2P_summary   

#Identifies the intercept and slope of regressing Temperature to Precipitation:
T2PInt<-T2P_summary$coefficients[1, 1] 
T2PSlope<-T2P_summary$coefficients[2, 1] 


#Regression of Precipitation to Temperature:
P2T<-lm(formula = y2 ~ y1, data = axis)
P2T_summary <- summary(lm(formula = y2 ~ y1, data = axis))
P2T_summary   

#Identifies the intercept and slope of regressing Precipitation to Temperature:
P2TInt<-P2T_summary$coefficients[1, 1] 
P2TSlope<-P2T_summary$coefficients[2, 1] 


#Create Plot:
ggplot(climate, aes(Month, Precip)) +
  geom_col() +
  geom_line(aes(y = T2PSlope*Temp + T2PInt), color = "red") +
  scale_y_continuous("Precipitation", sec.axis = sec_axis(~.*P2TSlope + P2TInt, name = "Temperature")) +
  scale_x_continuous("Month", breaks = 1:12) +
  theme(axis.line.y.right = element_line(color = "red"), 
        axis.ticks.y.right = element_line(color = "red"),
        axis.text.y.right = element_text(color = "red"), 
        axis.title.y.right = element_text(color = "red")) +
  ggtitle("Climatogram for Oslo (1961-1990)")

Most noteworthy is that a new "transformation function" works better with just two data points from the data set of each axes—usually the maximum and minimum values of each set. The resulting slopes and intercepts of the two regressions enable ggplot2 to exactly pair the plots of the minimums and maximums of each axis. As user4786271 pointed out, the two regressions transform each data set and plot to the other. One transforms the break points of the first y axis to the values of the second y axis. The second transforms the data of the secondary y axis to be "normalized" according to the first y axis. The following output shows how the axis align the minimums and maximums of each dataset:

使最大值和最小值匹配可能是最合适的;但是,这种方法的另一个好处是,如果需要,可以通过更改与主轴数据相关的编程行轻松地移动与次要轴相关的绘图。下面的输出只是将y1编程行中输入的最小降水量更改为“0”,从而将最小温度水平与“0”降水水平对齐。

从:y1<-(c(max(气候$ precp), min(气候$ precp)))

到:y1<-(c(max(气候$ precp), 0))

请注意,生成的新回归和ggplot2如何自动调整绘图和轴,以正确地将最低温度与“0”降水水平的新“基数”对齐。同样,可以很容易地提升Temperature图,使其更加明显。下面的图是通过简单地将上面提到的线更改为:

“日元<——(c(150年,55岁))”

上面的线表示温度曲线的最大值与“150”降水水平相吻合,温度曲线的最小值与“55”降水水平相吻合。再次注意,ggplot2和由此产生的新的回归输出如何使图保持与轴的正确对齐。

以上可能不是理想的输出;然而,这是一个例子,说明了如何容易地操纵图形,并且在图和轴之间仍然有正确的关系。 Dag Hjermann的主题的结合提高了与情节对应的轴的识别。