简体   繁体   中英

Plotting a bar plot of two variables and a line plot of third variable on a single plot in R

I am trying to plot a bar plot (with position ='identity', stat = 'identity' ) and a line plot on the same plot against months using ggplot2 package in R.

My data consists of 3 mainly concerned values

1- Global irradiance 2- Diffuse irradiance 3- Temperature

To make a bar plot, I have merged the values of Global and Diffuse irradiances in one molten dataframe. Whereas I have kept temperature values separate in an initial dataframe as I don't want it's bar plot with the irradiance values.

Now problem is I am unable to make ggplot from two different dataframes. The error I am getting using this approach is

Error: ggplot2 doesn't know how to deal with data of class uneval

even though class of both datasets is dataframe now.

On the other hand, I am confused on how to include my values in a single dataframe that I can plot all them together as bar and line plots.

My piece of code for data is:

library(ggplot2)
library(officer)
library(reshape2)

data <- "U://30-Power & Water//25 Renewables//WORK//Data//PVPlanner//PVPlanner.csv"

data <- read.table(data,skip = 36, header = T,  sep=";")
data <- data.frame(data[1:12,])
data$Month <- factor(data$Month,levels = c("Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"))

whereas my data looks like:

Month GHId GHIm Diffd Diffm  T24
1    Jan 3.27  101  0.92    29 13.3
2    Feb 3.92  110  1.23    34 13.3
3    Mar 5.30  164  1.58    49 13.9
4    Apr 6.18  185  1.89    57 14.9
5    May 6.93  215  2.00    62 16.4
6    Jun 7.53  226  1.80    54 18.4
7    Jul 7.42  230  1.87    58 21.1
8    Aug 7.06  219  1.58    49 22.0
9    Sep 5.97  179  1.39    42 21.3
10   Oct 4.50  140  1.26    39 18.7
11   Nov 3.53  106  0.99    30 15.9
12   Dec 2.90   90  0.86    27 13.3

The code for making a molten dataframe out of my data is:

dfd <- melt(data[,c('Month','GHId','Diffd')],id.vars = 1)

The code for my ggplot is:

ggplot() + geom_bar(dfd,aes(x = Month,y = value,fill = variable),stat = "identity",position = "identity")+geom_line(data,aes(Month, data[,6]), col=red)

I am trying to make this kind of plot: 在此处输入图片说明

I am looking forward to getting guidance on the type of approach that I can take either to work on a single dataframes or to call values from two different dataframes.

Thanks in advance! Regards

Ok.. I was able to spot out my mistake, If there are values from two dataframes we need to mentioned properly where exactly data is in our code like data = dfd in both the geom

OR

We need to code using exact arrangement of the code as mentioned in the function documentation!

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM