Hello I have a smooth scatter plot same plot I wanted try with ggplot with, can anyone help me i have created plot using ggplot but not able create curve line and diagonal line same as smooth scatter plot
data
A B cat
0.8803 0.0342 data1
0.9174 0.0331 data1
0.9083 0.05 data1
0.7542 0.161 data2
0.8983 0.0593 data2
0.8182 0.1074 data2
0.3525 0.3525 data3
0.5339 0.2288 data3
0.7295 0.082 data3
smooth scatter plot
df=read.table("test.txt", sep='\t', header=TRUE)
smoothScatter(df$B,df$A,,nrpoints=Inf,xlim=c(0,1),ylim=c(0,1), pch=20,cex=1, col=df$cat)
points(c(0,1),c(1,0),type='l',col='green',lty=2,lwd=2)
p=0:1000/1000
points((1-p)^2,p^2,type='l',col='red',lty=2,lwd=2)
ggplot script
ggplot(df, aes(x=B, y=A))+
geom_point()
If you're trying to draw lines based on an equation, you can define the equation and then use geom_line to draw that line with stat="function". Here's how you can draw the lines in ggplot and simulate the same look:
library(ggplot2)
curvy <- function(x) { ((1-x)^2)^2 }
straight <- function(x) 1-x
ggplot(df, aes(x=B, y=A))+
geom_point(size=3) +
geom_line(stat='function', fun=straight, color='green', linetype='dashed', size=1) +
geom_line(stat='function', fun=curvy, color='red', linetype='dashed', size=1) +
xlim(0,1) + ylim(0,1) +
theme_classic()
As for the fuzzy points, you can give ggblur a try here's the github. It wasn't available for the version I'm using.
The other way to draw lines on a plot via regression would be to use geom_smooth(). You'll want to specify the method there - for linear you can use "lm" - "loess" is used by default.
ggplot(df, aes(x=B, y=A))+
geom_point(size=3) +
geom_line(stat='function', fun=straight, color='green', linetype='dashed', size=1) +
geom_line(stat='function', fun=curvy, color='red', linetype='dashed', size=1) +
geom_smooth(method='lm', alpha=0.2, color='blue', fill='skyblue', linetype='dotted') +
xlim(0,1) + ylim(0,1) +
theme_classic()
Related
I am trying to make dual bar plot in single X axis, how to perform it? I know how to do with line plot. for example I am using mtcars data. Also i want to add legends and error line in that bars.
library(ggplot2)
scaleFactor <- max(mtcars$cyl) / max(mtcars$hp)
ggplot(mtcars, aes(x=disp)) +
geom_smooth(aes(y=cyl), method="loess", col="blue") +
geom_smooth(aes(y=hp * scaleFactor), method="loess", col="red") +
scale_y_continuous(name="cyl", sec.axis=sec_axis(~./scaleFactor, name="hp")) +
theme(
axis.title.y.left=element_text(color="blue"),
axis.text.y.left=element_text(color="blue"),
axis.title.y.right=element_text(color="red"),
axis.text.y.right=element_text(color="red")
)
the data would need to be restructured, in order to function properly with ggplot.
Here is how I did it with the example of three columns and rows of mtcars:
# Only use first 3 rows and columns
mtcarsmod <- mtcars[1:3, 1:3]
# Restructure data
Car <- rownames(mtcarsmod)
Part <- colnames(mtcarsmod)
Value <- as.vector(t(mtcarsmod))
mtcarsmod <- data.frame("Car"=rep(Car,each=length(Part)), "Part"=rep(Part, times=length(Car)), "Value"= Value)
# Visualize data
library(ggplot2)
# Have Cars on X axis
plot <- ggplot(mtcarsmod, aes(x=Car, y=Value, fill=Part)) +
geom_bar(position="dodge", stat="identity")
plot
# Have Variables on X axis
plot <- ggplot(mtcarsmod, aes(x=Part, y=Value, fill=Car)) +
geom_bar(position="dodge", stat="identity")
plot
# Have Cars on Y axis
plot <- ggplot(mtcarsmod, aes(x=Value, y=Car, fill=Part)) +
geom_bar(position="dodge", stat="identity")
plot
# Have Variables on Y axis
plot <- ggplot(mtcarsmod, aes(x=Value, y=Part, fill=Car)) +
geom_bar(position="dodge", stat="identity")
plot
I want to make a plot in ggplot2 like this
x <- 1:10
y <- rnorm(10) + x
df <- data.frame(x=x,y=y)
plot(x,y)
lines(x,y,type='c')
I like this type='c' style,R help tell me
"c" for empty points joined by lines
but how can I implement this type in ggplot2?
library(ggplot2)
ggplot(data=df,aes(x=x,y=y)) + geom_line() + geom_point(shape=21,size=3)
I mean, how to make a blank between the empty points and the lines? which linetype should I choose?
thank you very much
ggplot(data=df,aes(x=x,y=y)) +
geom_line() +
geom_point(shape=21, size=5, colour="white", fill="white") +
geom_point(shape=21,size=3) +
theme_bw()
I'd like to smooth the geom_lines and fill the area between. I've tried stat_smooth() to smooth the lines, and both geom_ribbon() and geom_polygon() but without success.
Apologies for the double barrel question.
bell <- data.frame(
month = c("Launch","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th"),
rate = c(0,.05,.12,.18,.34,.42,.57,.68,.75,.81,.83,.85,.87))
bell$month <- factor(bell$month, levels = rev(c("Launch","1st","2nd","3rd","4th","5th","6th","7th","8th","9th","10th","11th","12th")))
ggplot() +
theme_minimal() +
coord_flip() +
scale_fill_manual(values=cols) +
geom_line(data=bell, aes(x=month, y=.5-(rate/2), group=1), color='pink', size=1) +
geom_line(data=bell, aes(x=month, y=.5+(rate/2), group=1), color='pink', size=1) +
theme(legend.position='none', axis.ticks=element_blank(), axis.text.x=element_blank(),axis.title.x=element_blank())
One option is to calculate the points of the loess regression outside of ggplot and then plot them using geom_line (for a line) or geom_area for a filled area (geom_area is geom_ribbon, but with ymin fixed at zero).
Also, you don't need coord_flip. Instead, just switch your x and y mappings. This is necessary anyway if you want to fill underneath the curve.
In the example below I've created a numeric month variable for the regression. I've also commented out the scale_fill_manual line because your example doesn't provide a cols vector and the plot code doesn't produce a legend anyway. I've also commented out the legend.position='none' line as it's superfluous.
bell$month.num = 0:12
m1 = loess(rate ~ month.num, data=bell)
bell$loess.mod = predict(m1)
ggplot(bell, aes(y=month, group=1)) +
theme_minimal() +
#scale_fill_manual(values=cols) +
geom_area(aes(x=.5-(loess.mod/2)), fill='pink', size=1) +
geom_area(aes(x=.5+(loess.mod/2)), fill='pink', size=1) +
theme(#legend.position='none',
axis.ticks=element_blank(),
axis.text.x=element_blank(),
axis.title.x=element_blank())
If I plot this
dodge <- position_dodge(.35)
ggplot(mediat, aes(x=t, y=Value, colour=factor(act),group=id )) +
geom_point(position=dodge) + geom_errorbar(aes(ymin=Value-sdt, ymax=Value+sdt),
width=0, position=dodge) + theme_bw() + geom_smooth(method="lm",se=FALSE,
fullrange=TRUE)
I get this
As you can see the regression line is not plotted.
with +stat_smooth(method=lm, fullrange=TRUE, se = FALSE) the result is the same.
I've found that removing the "group=id" I can get the regression lines but
then
ggplot(mediat, aes(x=t, y=Value, colour=factor(act) ))+ geom_point(position=dodge) +
geom_errorbar(aes(ymin=Value-sdt, ymax=Value+sdt), width=0, position=dodge) +
theme_bw() + geom_smooth(method="lm",se=FALSE, fullrange=TRUE)
As you can see, now it plot the lines but I loose the dodge function by groups.
How can I get both things at once?. I mean, regression lines by "id" on the first uncluttered plot?
Any other solution with base plot, lattice or any other common package would also be welcome.
Regards
I start by giving you my example code:
x <- runif(1000,0, 5)
y <- c(runif(500, 0, 2), runif(500, 3,5))
A <- data.frame("X"=x,"Y"=y[1:500])
B <- data.frame("X"=x,"Y"=y[501:1000])
ggplot() +
stat_bin_hex(data=A, aes(x=X, y=Y), bins=10) +
stat_bin_hex(data=B, aes(x=X, y=Y), bins=10) +
scale_fill_continuous(low="red4", high="#ED1A3A")
It produces the following plot:
Now I want the lower hexagons to follow a different scale. Namely ranging from a dark green to a lighter green. How can I achieve that?
Update:
As you can see from the answers so far, I am asking myself whether there is a solution without using alpha scales. Also, using two plots with no margin or something similar is not an option for my specific application. Though they both are legitimate answers :)
Rather than trying to get two different fill scales in one plot you could alter the colours of the lower values, after the plot has been built. The basic idea is have two plots with the differing fill scales and then copy accross certain details from one plot to the other.
# Base plot
p <- ggplot() +
stat_bin_hex(data=A, aes(x=X, y=Y), bins=10) +
stat_bin_hex(data=B, aes(x=X, y=Y), bins=10)
# Produce two plots with different fill colours
p1 <- p + scale_fill_continuous(low="red4", high="#ED1A3A")
p2 <- p + scale_fill_continuous(low="darkgreen", high="lightgreen")
# Get fill colours for second plot and overwrite the corresponding
# values in the first plot
g1 <- ggplot_build(p1)
g2 <- ggplot_build(p2)
g1$data[[1]][,"fill"] <- g2$data[[1]][,"fill"]
# You can draw this now but there is only one legend
grid.draw(ggplot_gtable(g1))
To have two legends you can join the legends from the two plots together
# Bind the legends from the two plots together
g1 <- ggplot_gtable(g1)
g2 <- ggplot_gtable(g2)
g1$grobs[[grep("guide", g1$layout$name )]] <-
rbind(g1$grobs[[grep("guide", g1$layout$name )]],
g2$grobs[[grep("guide", g2$layout$name )]] )
grid.newpage()
grid.draw(g1)
Giving (from set.seed(10) prior to data generation)
This should provide more or less what you want
ggplot() +
stat_bin_hex(data=A, aes(x=X, y=Y, alpha=..count..), bins=10,fill="green") +
stat_bin_hex(data=B, aes(x=X, y=Y, alpha=..count..), bins=10,fill="red")
To avoid that the grey is disturbing due to the alpha one could underlay the plot with another white plot at the same location and darken the colours a bit, as suggested by the TO in the comments
#just the red to show the impact due to scale_alpha
ggplot() +scale_alpha_continuous(range=c(0.5,1))+ stat_bin_hex(data=A, aes(x=X, y=Y), bins=10,fill="white",show.legend = TRUE) +
+ stat_bin_hex(data=A, aes(x=X, y=Y, alpha=..count..), bins=10,fill="red",show.legend = TRUE) +
+ stat_bin_hex(data=B, aes(x=X, y=Y, alpha=..count..), bins=10,fill="green", show.legend=TRUE)+guides(fill=FALSE, alpha=FALSE)
An alternative, if you want more options to play with the colours, just create two plots and remove all the space between the two plots when combined with grid.arrange().
p1 <- ggplot() + stat_bin_hex(data=B, aes(x=X, y=Y), bins=10) +
scale_fill_continuous(low="red4", high="#ED1A3A") + xlab("") + theme(axis.text.x=element_blank(), axis.ticks.x=element_blank(), plot.margin=unit(c(1,1,-0.5,1), "cm")) + scale_y_continuous(limits = c(2.5, 5.5))
p2 <- ggplot() + stat_bin_hex(data=A, aes(x=X, y=Y), bins=10) + scale_fill_continuous(low="darkgreen", high="green") + theme(plot.margin=unit(c(-0.5,1,1,1), "cm")) + scale_y_continuous(limits = c(-0.5, 2.5))
grid.arrange(p1,p2)