I am trying to plot my two figures on the same page in R.
Two plots are: Scatter and bat plot
Used: par(mfrow=c(2,1))
p
s
where p is the bar plot and s is the scatter plot.
When I used the command: first p plot shows and at the end only s-- scatter plot is shown.
I know both the plots are there but could not fix it!!
I really need a help here.
There is small problem in code provided by OP. The wrong dataframe is used in scatter plot.
The correct implementation could be:
#The dataset read is has been modified to read from text as provided in OP
dataset <- read.table(text = "Category Jan Feb
Food 25 100
Makeup 10 150
Travel 200 120
Drinks 164 36", header = TRUE, stringsAsFactors = FALSE)
# mfrow setting will not have any effect on ggplot2 based
par(mfrow=c(2,1))
p<-ggplot(dataset, aes(x=Category, y=Jan)) + geom_bar(stat="identity",)
# OP has used just data for ggplot function to s
s<-ggplot(dataset, aes(x=Category, y=Feb)) + geom_point()
p
s
But the graphs will be drawn in separate pages.
grid.arrange() function gridExtra can be used to draw multiple ggplot based plots in same screen.
You can use multi-graph function and plot any number of graphs on the same page.
Examples below:
http://www.cookbook-r.com/Graphs/Multiple_graphs_on_one_page_(ggplot2)/
Note: it's a custom function, so it's not in any packages. You should just copy and paste, then run it in your console.
Related
I am plotting two histograms in R by using the following code.
x1<-rnorm(100)
x2<-rnorm(50)
h1<-hist(x1)
h2<-hist(x2)
plot(h1, col=rgb(0,0,1,.25), xlim=c(-4,4), ylim=c(0,0.6), main="", xlab="Index", ylab="Percent",freq = FALSE)
plot(h2, col=rgb(1,0,0,.25), xlim=c(-4,4), ylim=c(0,0.6), main="", xlab="Index", ylab="Percent",freq = FALSE,add=TRUE)
legend("topright", c("H1", "H2"), fill=c(rgb(0,0,1,.25),rgb(1,0,0,.25)))
The code produces the following output.
I need a visually good looking (or stylistic) version of the above plot. I want to use ggplot2. I am looking for something like this (see Change fill colors section). However, I think, ggplot2 only works with data frames. I do not have data frames in this case. Hence, how can I create good looking histogram plot in ggplot2? Please let me know. Thanks in advance.
You can (and should) put your data into a data.frame if you want to use ggplot. Ideally for ggplot, the data.frame should be in long format. Here's a simple example:
df1 = rbind(data.frame(grp='x1', x=x1), data.frame(grp='x2', x=x2))
ggplot(df1, aes(x, fill=grp)) +
geom_histogram(color='black', alpha=0.5)
There are lots of options to change the appearnce how you like. If you want to have the histograms stacked or grouped, or shown as percent versus count, or as densities etc., you will find many resources in previous questions showing how to implement each of those options.
I have a (21,100)-array and want to plot it as 2D-Histogram (heatmap).
If I plot it naively with histogram2d(A, nbins= 20) it only plots the first 21 points.
I tried to loop it, but then I had 100 histograms with 21 points.
Another idea would be to put the data in a (2100)-array but this seems like a bad idea.
Addition:
I have a scatter plot/data and want it shown as a heatmap. The more points in one bin the "darker" the color.
So I have 21 x-values each with 100 y-values.
Here it is a typical scenario for a heatmap plot:
using Plots
gr()
data = rand(21,100)
heatmap(1:size(data,1),
1:size(data,2), data,
c=cgrad([:blue, :white,:red, :yellow]),
xlabel="x values", ylabel="y values",
title="My title")
I am using Julia for Financial Data Processing and then plotting graphs based on the financial data.
on X-Axis of graph I am plotting dates (per day prices)
on Y-Axis I am plotting Stock Prices, MovingAverage13 and MovingAverage21
I am currently using DataFrames to plot the data
Code-
df=DataFrame(x=dates,y1=pricesClose,y2=m13,y3=m21)
l1=layer(x="x",y="y1",Geom.line,Theme(default_color=color("blue")));
l2=layer(x="x",y="y2",Geom.line,Theme(default_color=color("red")));
l3=layer(x="x",y="y3",Geom.line,Theme(default_color=color("green")));
p=plot(df,l1,l2,l3);
draw(PNG("stock.png",6inch,3inch),p)
I am Getting the graphs correctly but I am not able to add a Legend in the Graph that shows
blue line is for Close Prices
red line is for moving average 13
green line is for moving average 21
How can we add a legend to the graph?
I understand from the comments in this link that currently it is not possible to get a legend for a list of layers.
Gadfly is based on Hadley Wickhams's ggplot2 for R and thus the usual pattern is to arrange data into a DataFrame with a discrete column for labelling purposes. In your case, this approach would look like:
x = 1:10
df1 = DataFrame(x=x, y=2x, label="double")
df2 = DataFrame(x=x, y=x.^2, label="square")
df3 = DataFrame(x=x, y=1./x, label="inverse")
df = vcat(df1, df2, df3)
p = plot(df, x="x", y="y", color="label", Geom.line,
Scale.discrete_color_manual("blue","red", "green"))
draw(PNG("stock.png", 6inch, 3inch), p)
Now you can try with manual_color_key.
The only change in your code is needed here:
p=plot(df,l1,l2,l3,
Guide.ylabel("Some text"),
Guide.title("My title"),
Guide.manual_color_key("Legend", ["I'm blue l1", "I'm red l2", "I'm green l3"], ["blue", "red", "green"]))
I am trying to create a heatmap combined with a barplot, such that at the end of every row is a bar with length relevant to that row. The idea is to combine something like the following two into one:
library(gplots)
data(mtcars)
x <- as.matrix(mtcars[,2:11])
hm<-heatmap(x)
barplot(mtcars[hm$rowInd,"mpg"],horiz=T,names.arg=row.names(mtcars)[hm$rowInd],las=2,cex.names=0.7,col="purple",2)
My question is how to combine the two while making the rows and bars align?
Thanks.
You can't combine the plots because (as per the documentation) heatmap() uses layout and draws the image in the lower right corner of a 2x2 layout. Consequentially, it can not be used in a multi column/row layout, i.e., when par(mfrow = *) or (mfcol = *) has been called.
Your best best would be to use ggplot2 and gridExtra to combine the graphs. For this both the heatmap and bar plot need to be created using ggplot.
You can find a heatmap on ggplot2 tutorial here.
Once you have your two plots combine them using the following commands:
#Create the plots
g1 <- heatmap
g2 <- barplot
#Arrange them in a grid
gg1 <- ggplot_gtable(ggplot_build(g1))
gg2 <- ggplot_gtable(ggplot_build(g2))
grid.arrange(gg1, gg2, ncol=2)
I'm trying to inset a plot using ggplot2 and annotation_custom (the plot is actually a map that I'm using to replace the legend). However, I'm also using facet_wrap to generate multiple panels, but when used with annotation_custom, this reproduces the plot in each facet. Is there an easy way to insert the plot only once, preferably outside the plotting area?
Here is a brief example:
#Generate fake data
set.seed(9)
df=data.frame(x=rnorm(100),y=rnorm(100),facets=rep(letters[1:2]),
colors=rep(c("red","blue"),each=50))
#Create base plot
p=ggplot(df,aes(x,y,col=colors))+geom_point()+facet_wrap(~facets)
#Create plot to replace legend
legend.plot=ggplotGrob(
ggplot(data=data.frame(colors=c("red","blue"),x=c(1,1),y=c(1,2)),
aes(x,y,shape=colors,col=colors))+geom_point(size=16)+
theme(legend.position="none") )
#Insert plot using annotation_custom
p+annotation_custom(legend.plot)+theme(legend.position="none")
#this puts plot on each facet!
This produces the following plot:
When I would like something more along the lines of:
Any help is appreciated. Thanks!
In the help of annotation_custom() it is said that annotations "are the same in every panel", so it is expected result to have your legend.plot in each facet (panel).
One solution is to add theme(legend.position="none") to your base plot and then use grid.arrange() (library gridExtra) to plot both plots.
library(gridExtra)
p=ggplot(df,aes(x,y,col=colors))+geom_point()+facet_wrap(~facets)+
theme(legend.position="none")
grid.arrange(p,legend.plot,ncol=2,widths=c(3/4,1/4))