R语言 组合条形图和折线图,不同的y轴,无ggplot

vfh0ocws  于 2023-09-27  发布在  其他
关注(0)|答案(2)|浏览(88)

我想创建一个类似的图,但没有ggplot2:Combining Bar and Line chart (double axis) in ggplot2
寻找一个答案,允许更简单的视觉比ggplot。ggplot的主要问题是调整副轴和不那么简单的图形。对于学术出版物来说,精简的图表更可取。

nr7wwzry

nr7wwzry1#

虽然我同意Gregor的观点,即具有最小主题的ggplot可能是正确的工具,但我认为这很有趣,给予尝试使用base R。这比我想象的要难

# Define some data, two sets of values to plot
 y1 = c(10,20,30)
 y2 = c(40,60,53)
 
 # Against one group variable
 group = c("A","B","C")
 
 # How much space to leave between the bars?
 space=0.2
 
 # Give some room for the second y-axis
 par(mar=c(5,4,4,5)+.1)
 
 # Work out the x-limits of the graph
 xlim=c(0,space+(1+space)*length(group))
 
 # Work out the x-location of the bar centres/points
 x=(1+space)*seq_along(group)-0.5
 
 # Plot the bar graph
 barplot(y1, space=space, xlim=xlim,col="red", xlab="Group", ylab="y1")
 
 # Add the x=axis
 axis(1, labels=group, at=x)

 # Start a new graph without overwriting the old one
 par(new=TRUE)
 
 # Add the line graph
 plot(x, y2, axes=F, type="b", xlim, ann=F,pch=20)
 
 # Add the second y axis
 axis(4)
 
 # Add the second y label
 mtext("y2", side=4, line=3)

lg40wkob

lg40wkob2#

为了完整起见,这里有一个使用ggplot2的非常相似的图表:

ggplot(data.frame(Group, y1, y2), aes(Group)) +
  geom_col(aes(y = y1), fill = "red", color = "black") +
  geom_line(aes(y = (y2-40)*1.5, group = 1)) +
  geom_point(aes(y = (y2-40)*1.5, group = 1)) +
  scale_y_continuous(sec.axis = sec_axis(trans = ~(.x/1.5+40), name = "y2")) +
  ggthemes::theme_par()

相关问题