一个水平行的ggplot2图例项

时间:2021-06-07 14:59:57

This may seem like a stupid question, but I am a little confused.

这似乎是个愚蠢的问题,但我有点困惑。

It seems that the code I wrote and tested last week has now suddenly decided to change the output even though nothing in the code or the version of R or Rstudio has changed.

我上周编写和测试的代码现在似乎突然决定更改输出,尽管代码或R或Rstudio的版本中没有任何更改。

Previously when I drew a plot with ggplot2 and asked for the legend to appear at the bottom of the plot, it automatically oriented the items into a single horizontal row. Now when I run the same code it places the item in a number of 2-row columns.

在此之前,当我使用ggplot2绘制一个图并要求图例出现在图的底部时,它会自动将项目定向到一个水平行。现在,当我运行相同的代码时,它将项目放置在许多2行列中。

Here's an example...

这里有一个例子……

mtcars$cyl <- (1:32)
subcars <- subset(mtcars, cyl<10)
subcars$cyl <- as.factor(subcars$cyl)

ggplot(subcars, aes(carb, mpg, group=cyl, colour=cyl)) + 
  geom_line() +
  theme_classic() +
  theme(plot.title = element_text(size = rel(2), face="bold", vjust=-4)) +
  theme(legend.position = "bottom") +
  theme(legend.direction = "horizontal") +
  labs(title="Title") 

As you can see, I have already tried adding in the line theme(legend.direction = "horizontal") but I still get a legend which displays the items in 5 2-row columns (yes, its not even just in two rows).

如您所见,我已经尝试添加线主题(legend)。方向= "水平线")但我还是得到了一个图例,它显示了5个2行列中的项目(是的,它甚至不只是两行)。

Now I can only assume that there has been some update that I was not aware of or something, so I'm willing to accept that I need to come up with a new strategy for dealing with this problem (which just wasn't a problem last week). Although I am a little bit confused about why my code has suddenly decided to stop working (any input on this welcome), I'm more interested in finding a fix for the immediate problem of my legend items being displayed in a strange configuration.

现在我只能假设有一些我没有意识到的更新,所以我愿意接受我需要提出一个新的策略来解决这个问题(这在上周并不是一个问题)。尽管我对为什么我的代码突然决定停止工作(关于这个欢迎的任何输入)感到有点困惑,但我更感兴趣的是找到一个修复方案,解决我的legend项以奇怪的配置显示的直接问题。

1 个解决方案

#1


28  

Add this to your plot:

把这个加到你的情节中:

+ guides(colour = guide_legend(nrow = 1))

#1


28  

Add this to your plot:

把这个加到你的情节中:

+ guides(colour = guide_legend(nrow = 1))