[英]Multiple Data Frame Plot Custom Legend and X Axis Breaks?
The data is 1965-2019 Renewable Energy Vs Alternative Energy Sources.数据是 1965-2019 可再生能源与替代能源的对比。 I have two issues I am trying to tackle here.
我有两个问题要在这里解决。 I would like to 1) Add a custom legend signifying the two colors and naming them accordingly.
我想 1) 添加一个自定义图例,表示两个 colors 并相应地命名它们。 2) I want to know if there is an easy way to create breaks in the x-axis without working too hard, essentially only showing every other year or every 5 years as breaks for better interpretability.
2) 我想知道是否有一种简单的方法可以在不努力工作的情况下在 x 轴上创建中断,基本上只每隔一年或每 5 年显示一次中断以获得更好的可解释性。 My code and the current output plot are below.
我的代码和当前的output plot如下。 It is an overlay of two data frames, each having a simple x and y variable.
它是两个数据帧的叠加,每个数据帧都有一个简单的 x 和 y 变量。
renew_plot <- ggplot(NULL, aes(x, y)) +
xlab('Years') +
ylab('Terawatt/Hr') +
ggtitle('Global Energy Consumption By Year') +
geom_point(data = renew_tot_energy_con_by_year, col = "green") +
geom_point(data = oth_tot_energy_con_by_year, col = "blue")
renew_plot
The main issue I am running into is figuring out the legend since they are from separate data frames.我遇到的主要问题是弄清楚图例,因为它们来自不同的数据框。 Is there a way I can create a custom legend with two simple geom points that I can match the same color as my plot?
有没有办法用两个简单的几何点创建一个自定义图例,我可以匹配与我的 plot 相同的颜色? That would be the easiest I believe.
我相信那将是最简单的。 I am not sure the best way to go about this.
我不确定有关此问题的最佳方法 go。
I'm guessing from your squished x axis that your x data in at least one of the two data sets is in character or factor format, so ggplot2 is not automatically selecting "pretty" breaks but rather showing all of them.我从你压扁的 x 轴猜测你的 x 数据在至少两个数据集中的一个是字符或因子格式,所以 ggplot2 不会自动选择“漂亮”的中断,而是显示所有这些。 You could either convert the x values to numeric (eg
a$x = as.numeric(a$x)
if its character or a$x =
as.numeric(as.character(a$x))` if its factor) or specify discrete breaks like below.您可以将 x 值转换为数字(例如
a$x = as.numeric(a$x)
如果它的字符或a$x =
as.numeric(as.character(a$x))` 如果它的因子)或指定如下所示的离散中断。
To get the source into the legend, you could map the source name to the color aesthetic.要将来源添加到图例中,您可以将来源名称 map 添加到颜色美学中。
a <- data.frame(x = as.character(1990:2021), y = mtcars$mpg)
b <- data.frame(x = as.character(1990:2021), y = mtcars$hp)
library(ggplot2)
ggplot(NULL, aes(x,y)) +
geom_point(data = a, aes(color = "a")) +
geom_point(data = b, aes(color = "b")) +
scale_x_discrete(breaks = seq(1990, 2020, by = 5))
Output without the scale_x_discrete part: Output 没有 scale_x_discrete 部分:
Output with the scale_x_discrete part: Output 与 scale_x_discrete 部分:
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.