Related
The following sample or R code displays contour levels and the data points used in generating the contours.
n <- 10
x <- c(rnorm(n,-1,0.5), rnorm(n,1,0.5))
y <- c(rnorm(n,-1,1), rnorm(n,1,0.5))
df <- data.frame(x,y)
# categorise the points
df$cat <- sample(c(1,2), n, replace=T)
library(ggplot2)
p <- ggplot(df)
# for manual colouring of points, but not showing contours due to error
#p <- p + geom_point(aes(x=x,y=y,col=factor(cat)))
#cols <- c("1"="red", "2"="blue")
#p <- p + scale_color_manual(values=cols)
# this works fine except I am not controlling the colours
p <- p + geom_point(aes(x=x,y=y,col=cat))
p <- p + geom_density2d(aes(x=x,y=y,color=..level..))
print(p)
I am able to colour the points according to their binary category (see commented out code above) manually if I do not display the contours, but adding the contours results in a "Continuous value supplied to discrete scale" error.
Various attempts have failed.
The question: Is it possible to colour the points (according to category) and independently colour the contour levels (according to height)?
You can try
library(tidyverse)
df %>%
ggplot(aes(x=x,y=y)) +
stat_density_2d(aes(fill = ..level..), geom = "polygon") +
geom_point(aes(color=factor(cat)), size=5) +
theme_bw()
Or switch to points where fill is working like shape=21
df %>%
ggplot(aes(x=x,y=y)) +
geom_density2d(aes(color=..level..))+
geom_point(aes(fill=factor(cat)),color="black",shape=21, size=5) +
theme_bw() +
scale_fill_manual(values = c(2,4)) +
scale_color_continuous(low = "green", high = "orange")
or try to add scale_color_gradientn(colours = rainbow(10)) instead.
Goal: add numeric labels(number of bar on the plot) to legend, e.g 1.Company X
2.Company Y
3.Company Z
library(ggplot2)
require(scales)
companies = c('Company X','Company Y','Company Z')
profits = c(100,200,300)
data1 = data.frame(companies,profits)
CP <- ggplot(data1, aes(x = data1$companies,y = data1$profits,fill =data1$companies )) +
geom_bar(stat = 'identity') +
scale_x_discrete(name = "Companies",labels = 1:length(data1$companies))
Currently I have
What you might be looking for is paste:
newcompanies <- paste(1:50,companies,sep=".")
Personal (style) suggestion:
Search how you can change the colours to one colour-range. For fifty companies this colour-range will be confusing.
You can use seq_along and paste to make the plot you want as follow:
ggplot(data1, aes(x=seq_along(companies), weight=profits,
fill=paste(seq_along(companies), companies))) +
geom_bar() +
scale_fill_discrete("Companies") +
labs(x="Company Labels", y="Count")
Does somebody know a alternative method for ordering stacks of a ggplot2 bar graph?
I used to use for example
library(ggplot2)
library(plyr)
a <- cbind(rep("a",5),sample(1:100,5), rep_len(c("1","2","3"),5))
b <- cbind(rep("b",7),sample(1:100,7), rep_len(c("1","2","3"),7))
c <- cbind(rep("c",3),sample(1:100,3), rep_len(c("1","2","3"),3))
d <- cbind(rep("d",10),sample(1:100,10), rep_len(c("1","2","3"),10))
e <- cbind(rep("e",15),sample(1:100,15), rep_len(c("1","2","3"),15))
dat <- rbind(a,b,c,d,e)
colnames(dat) <- c("x","count","example")
dat <- as.data.frame(dat)
dat$x <- as.character(dat$x)
dat$count <- as.numeric(dat$count)
dat$example <- as.character(dat$example)
GP <- ggplot(dat, aes(x= reorder(x, count, sum), y=count, fill = example, order = desc(count)))+
geom_bar(stat="identity", fill= "grey", colour= "black", size = 1)+
coord_flip() +
scale_y_continuous()+
scale_x_discrete('')+
#scale_fill_brewer()+
labs(y="")+
theme_bw()+
theme(axis.text.y=element_text(size=8,face="bold"),
axis.text.x=element_text(size=10,face="bold"),
axis.title.x=element_text(size=16,face="bold"),
axis.title.y=element_text(size=16,face="bold"),
plot.title=element_text(size=16,face="bold"),
strip.text.x = element_text(size=10,face="bold"),
strip.background = element_blank())
print(GP)
to create graphs like
however in version 2.0.0 of ggplot2 order() has been removed. and now the graph will be like:
Does anybody know a alternative?
Tanks
I am using ggplot2 for a multiplot. Althoug after a lot of tweaking, I still face
problems as:
Some free space gets plotted on each side (left/right) of each plot. I have marked this on the right side of each plot.
Plots are not aligned by the left side. This problem is clearly observed in the bottom plot
Y axis label is much far away from the plots. Can I reduce this separation?
Multiplot is:
I used the following R code for the same:
p1 <- ggplot(data = dplots[[1]],aes(timestamp,power/1000))+ geom_line()+
ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+labs(title="room1")
p2 <- ggplot(data = dplots[[2]],aes(timestamp,power/1000))+ geom_line()+
ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="room2")
p3 <- ggplot(data = dplots[[6]],aes(timestamp,power/1000))+ geom_line()+
ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="room3")
p4 <- ggplot(data = dplots[[4]],aes(timestamp,power/1000))+ geom_line()+
ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="room4")
p5 <- ggplot(data = dplots[[5]],aes(timestamp,power/1000))+ geom_line()+
ylab("")+theme(axis.text.x=element_blank(),axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="room5")
p6 <- ggplot(data = dplots[[3]],aes(timestamp,power/1000))+ geom_line()+
ylab("")+theme(axis.title.x=element_blank(),axis.ticks.x=element_blank(),plot.margin = unit(c(-0.3,1,-0.3,1), "cm"))+ labs(title="Chiller") +
scale_x_datetime(labels= date_format("%d-%m-%y",tz ="UTC"),breaks = pretty_breaks(8))
grid.arrange(p1,p2,p3,p4,p5,p6,nrow=6,ncol=1,heights=c(0.15,0.15,0.15,0.15,0.15,0.15),left="Power (KW)")
The dataset (dplots) is stored at the link.
Probably the easiest solution is to combine the dataframes in the list in one dataset. With rbindlist from the data.table package you can also include id's for each dataframe:
library(data.table)
# bind the dataframes together into one datatable (which is an enhanced dataframe)
DT <- rbindlist(dplots, idcol = "id")
# give names to the id's
DT$id <- factor(DT$id, labels = c("room 1","room 2","room 3", "room 4","room 5","Chiller"))
library(ggplot2)
ggplot(DT, aes(x = timestamp, y = power)) +
geom_line() +
scale_x_datetime(expand = c(0,0)) +
facet_grid(id ~ ., scales="free_y") +
theme_bw()
this results in the following plot:
With your existing code, use cowplot package:
library(cowplot)
plot_grid(p1,p2,p3,p4,p5,p6,ncol=1,align = "v")
I've created a plot of categorical data using facet in ggplot.
Example script here:
#script to produce plot with dummy data
rm(list=ls(all=TRUE))
library(ggplot2)
require(gridExtra)
#put dummy data in df
dummy_data<-data.frame(experiment_number=c(rep("exp_1",15),rep("exp_2",15)),
group=rep(c("A","B","C"),5),yvalue=runif(30, 0.0, 0.05))
# make plot
plot1<-ggplot(data = dummy_data)+
geom_point(aes(x = group, y = yvalue,
colour=group,shape=group),size=3.5,position = position_jitter(w = 0.2)) +
facet_wrap( ~ experiment_number) +
ylab("yvalue") +
xlab("")
#plot
plot1
I now want to add text & bars below the plot to show the p values relating to a statistical test between the groups -an example where I've just drawn it in my hand is attached (p values just made up).
Note the p values will be different in the two different panels. I've played around with annotate & custom annotate but cant seem to get it to work. Any ideas?
thanks v much
Here's a totally ridiculous way of doing something similar to what you are asking for. I used geom_errorbar for the bars, so I had to flip the coordinate system. Anyway, you should be able to customize this to do what you need.
rm(list=ls(all=TRUE))
library(ggplot2)
#put dummy data in df
dummy_data<-data.frame(experiment_number=c(rep("exp_1",15),rep("exp_2",15)),
group=rep(c("A","B","C"),5),yvalue=runif(30, 0.0, 0.05))
# make plot
plot1<-ggplot(data = dummy_data)+
geom_point(aes(y = group, x = yvalue, #changed x and y
colour=group,shape=group),size=3.5,position = position_jitter(h = 0.2)) + # changed w=... to h=...
facet_wrap( ~ experiment_number) +
xlab("yvalue") +
ylab("") + coord_flip() # flipped coordinate system
#plot
rng <- range(dummy_data$yvalue) # range
df.lines <- data.frame(ymin=LETTERS[1:3], ymax=LETTERS[c(2,3,1)], x=rng[1]-diff(rng)*1:3/12) #data for geom_errorbar
# data for geom_text
df.txt <- data.frame(y=c("AB", "BC", "B"),
x=rng[1]-diff(rng)*(1:3+.5)/12,
label=c("p=0.003", "p=0.05", "p=0.6",
"p=0.2", "p=0.1", "p=0.05"),
experiment_number=rep(c("exp_1", "exp_2"), each=3))
# add some space and geom_errorbar and geom_text
plot2 <- plot1 + scale_x_continuous(limits=c(rng[1]-diff(rng)/3, rng[2]+diff(rng)/5)) +
geom_errorbar(data=df.lines, aes(x=x, ymin=ymin, ymax=ymax)) +
scale_y_discrete(breaks=LETTERS[1:3], limits=c("A", "AB", "B", "BC", "C")) +
geom_text(data=df.txt, aes(x=x, y=y, label=label), xjust=0.5)
plot2