在 R ggplot 中绘制多列并使图例正确
数据框架,有5列和51行,如下:
Var1 | var2 | 我有一个 |
---|---|---|
1990 | 2.2 | 4.1 |
1991 | 2.3 | 4.4 |
我想绘制绘制,因为多年的列是多年来每个VAR的趋势的列。
我尝试了:
lt <- c("VAR2" = "twodash", "VAR3" = "dotted", "VAR4" = "dashed", "VAR5" = "solid")
ggp1 <- ggplot(DATAFRAME, aes(VAR1)) + # Create ggplot2 plot
geom_line(aes(y = VAR2, linetype = "twodash", group=1, )) +
geom_line(aes(y = VAR3, linetype = "dotted", group=1)) +
geom_line(aes(y = VAR4, linetype = "dashed", group=1)) +
geom_line(aes(y = VAR5, linetype = "solid", group=1)) +
labs(y = "number of parties in government", x= "year", lintype = "Legend")+
scale_linetype_manual(values = lt)
ggp1
但是它不起作用。我该怎么办?
谢谢大家的帮助。
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
这应该做到:
这里的技巧是,当您以这种方式创建美学时(例如,
lineType =“ var2” var2 “
或lineType =“ twodash”
,ggplot2将它们变成一个因素,并按字母顺序排序级别。在您的原始代码中,级别将是按顺序,虚线,点缀,固体,固体的, 然后将线型值的向量放在ggplot
中我上面做的是将级别放在预期的顺序中, 设置背景中创建的因子的级别。
还指定 在
scale_linetype_manual /I.SSTATIC.NET/BQOHO.PNG“ alt =”“>
在2022-04-12上由(v2.0.1)
This should do it:
The trick here is that when you create aesthetics this way (e.g.,
linetype = "VAR2"
orlinetype = "twodash"
, ggplot2 will turn them into a factor and order the levels alphabetically. In your original code, the levels would be, in order, dashed, dotted, solid and twodash. What I did above was to put the levels in the intended order and then gave the vector of line-type values. Another catch is thatggplot
wants that vector to be un-named.You could also specify
breaks
inscale_linetype_manual
to set the levels of the factor that is created in the background. Then, your code would work as well.Created on 2022-04-12 by the reprex package (v2.0.1)
要将名称添加到图例中,您可以遵循u/DaveArmstrong的答案,但可以说更好的方法是将数据集转换为“长格式”或 整洁的数据框。
总体思路是每一列代表一个变量,每一行代表一个观察值。列布局应为 年 |变量|值 而不是
年份| VAR1 | VAR2 | VAR3...
。有很多方法可以转换数据框。一种非常简单的方法是使用pivot_longer()
,如下所示:To get the names into the legend, you can follow the answer from u/DaveArmstrong, but the arguably much better way would be to transform your dataset into a "long form" or Tidy Dataframe.
The general idea is that each column represents one variable and each row represents an observation. The column layout should be
year | variable | value
instead ofyear | VAR1 | VAR2 | VAR3...
. There are lots of ways to convert your dataframe. A pretty straightforward way is to usepivot_longer()
as you'll see below:您还可以使用
pivot_wider()
将数据转换,因此您无需多次调用Geom_line
。然后,您也可以将所有变量都馈入新变量。you can also transpose the data with
pivot_wider()
so you don't have to callgeom_line
multiple times. You then can feed in the new variable with all of your variables to linetype as well.