This question already has answers here:
Plotting half circles in R
(3 answers)
Closed 2 years ago.
I'd like to add points that are multicoloured dots, with one half in blue for ex. and one half in red. If possible, I'd like to be able to do it with more than 2 colors, for example 4 quarters, each with a color.
Is that at all possible?
I know I can superimpose several dots of different sizes, each with a color, resulting in a concentric multicolored dot. But this is not what I am after.
For context, I am using these points for cities in a map.
Here is a small example, with each city having a unicolored dot. But I would like each city to have a dot that has two halves, each one with a color.
require(ggmap);
citiesnames=c("Madrid","Toledo","Valencia","Granada")
cities=str_c(citiesnames,"Spain",sep=", ");
geo=geocode(cities);
lon=geo$lon;
lat=geo$lat;
coord=mapproject(lon, lat,proj="mercator");
map("world","Spain",fill=T,col="ivory",proj="mercator");
points(coord$x[1], coord$y[1], pch=16, cex=1.2, col="black")
points(coord$x[2],coord$y[2], pch=16, cex=1.2, col="red")
points(coord$x[3], coord$y[3], pch=16, cex=1.2, col="blue")
points(coord$x[4], coord$y[4], pch=16, cex=1.2, col="green4")
Any help greatly appreciated.
As I mentioned in the comments you can refer to this post for doing what you want. For documentation purposes I add an answer which resolve the issue:
You can add two half circles (pie charts) to your graph using these two functions:
upper.half.circle <- function(x,y,r,nsteps=100,...){
rs <- seq(0,pi,len=nsteps)
xc <- x+r*cos(rs)
yc <- y+r*sin(rs)
polygon(xc,yc,...)
}
lower.half.circle <- function(x,y,r,nsteps=100,...){
rs <- seq(0,pi,len=nsteps)
xc <- x-r*cos(rs)
yc <- y-r*sin(rs)
polygon(xc,yc,...)
}
Later when you are piloting you should set asp = 1 to get the half-circles.
plot(1, type="n",axes=F,xlab="", ylab="",xlim=c(0,200),ylim=c(0,200), asp = 1)
upper.half.circle(15,170,10,nsteps=1000,col='red')
lower.half.circle(15,170,10,nsteps=1000,col='blue')
Here's the result of this code:
You can later edit the fictions for getting quarters or whatever you need.
Related
par(mfrow=c(1,2))
Trigen <- data.frame(OTriathlon$Gender,OTriathlon$Swim,OTriathlon$Bike,OTriathlon$Run)
colnames(Trigen) <- c("Gender","Swim","Bike","Run")
res <- split(Trigen[,2:4],Trigen$Gender)
pairs(res$Male, pch="M", col = 4)
points(res$Female, pch ="F", col= 2)
Basically, Customize the pairs plot, so where the plot symbol and color of each data point represents
gender.
I did some random things in the code but the issue that I am facing is that I cant add female points to the existing plot. After running the points code it just stays the same doesn't get updated
There is no need to call points sevral times, because you can use the factor directly as a color. Example:
plot(iris[,c(2,3)], col=iris$Species)
I want to generate canonical correspondence analysis(CCA) plot, to show the influence of environmental parameters on species distribution using this code:
spe <- read.csv("spe.csv", row.names=1, sep=";")
env <- read.csv("env.csv", row.names=1, sep=";")
ccamodel <- cca(spe~., env)
plot(ccamodel, xlim=c(-1.5,2), ylim=c(-1,1.5), display=c("sp","cn"))
Here is the output generated where the environmental variables and species name are highlighted in blue and red respectively.
My questions: How I can put the same symbol as a filled circle or a filled square before or after each species name in the plot?
Thanks in advance
I cannot quite match your plot. The scaling of the biplot is different but otherwise this accomplishes what you want.
out <- plot(ccamodel, type="n", xlim=c(-2.5, 2.75), ylim=c(-1, 1.5))
text(ccamodel, dis="bp", scaling="species", col="blue", cex=.8)
points(ccamodel, pch=16, scaling="species", display="sp", col="red")
text(ccamodel, dis="species", scaling="species", col="red", cex=.8, pos=4)
The text is shifted to the right of the points for clarity. The pos= argument sets the position. If you leave it out the text is centered on top of the point, values of 1 - 4 put it below, left, over, and right of the point.
This question already has an answer here:
Ordering of points in R lines plot
(1 answer)
Closed 3 years ago.
I used plot(x, y, type="p") to draw a scatter plot, and it seems right (Figure 1). However, when using plot(x, y, type="l") to draw a line, there are some mussy lines (Figure 2). Why didn't it a "single" line?
Looks like your x vector needs to be sorted, when using line plots, the order in which your points are submitted is very important as the lines are drawn connecting one point to the next one.
y <- y[order(x)]
x <- x[order(x)]
# now you can make your plot
plot(x, y, type="l")
Scatter plots can be hard to interpret when many points overlap, as such overlapping obscures the density of data in a particular region. One solution is to use semi-transparent colors for the plotted points, so that opaque region indicates that many observations are present in those coordinates.
Below is an example of my black and white solution in R:
MyGray <- rgb(t(col2rgb("black")), alpha=50, maxColorValue=255)
x1 <- rnorm(n=1E3, sd=2)
x2 <- x1*1.2 + rnorm(n=1E3, sd=2)
dev.new(width=3.5, height=5)
par(mfrow=c(2,1), mar=c(2.5,2.5,0.5,0.5), ps=10, cex=1.15)
plot(x1, x2, ylab="", xlab="", pch=20, col=MyGray)
plot(x1, x2, ylab="", xlab="", pch=20, col="black")
However, I recently came across this article in PNAS, which took a similar a approach, but used heat-map coloration as opposed to opacity as an indicator of how many points were overlapping. The article is Open Access, so anyone can download the .pdf and look at Figure 1, which contains a relevant example of the graph I want to create. The methods section of this paper indicates that analyses were done in Matlab.
For the sake of convenience, here is a small portion of Figure 1 from the above article:
How would I create a scatter plot in R that used color, not opacity, as an indicator of point density?
For starters, R users can access this Matlab color scheme in the install.packages("fields") library, using the function tim.colors().
Is there an easy way to make a figure similar to Figure 1 of the above article, but in R? Thanks!
One option is to use densCols() to extract kernel densities at each point. Mapping those densities to the desired color ramp, and plotting points in order of increasing local density gets you a plot much like those in the linked article.
## Data in a data.frame
x1 <- rnorm(n=1E3, sd=2)
x2 <- x1*1.2 + rnorm(n=1E3, sd=2)
df <- data.frame(x1,x2)
## Use densCols() output to get density at each point
x <- densCols(x1,x2, colramp=colorRampPalette(c("black", "white")))
df$dens <- col2rgb(x)[1,] + 1L
## Map densities to colors
cols <- colorRampPalette(c("#000099", "#00FEFF", "#45FE4F",
"#FCFF00", "#FF9400", "#FF3100"))(256)
df$col <- cols[df$dens]
## Plot it, reordering rows so that densest points are plotted on top
plot(x2~x1, data=df[order(df$dens),], pch=20, col=col, cex=2)
You can get a similar effect by doing hexagonal binning, divide the region into hexagons, color each hexagon based on the number of points in the hexagon. The hexbin package has functions to do this and there are also functions in the ggplot2 package.
You can use smoothScatter for this.
colramp = colorRampPalette(c('white', 'blue', 'green', 'yellow', 'red'))
smoothScatter(x1, x2, colramp=colramp)
I'm trying to build an histogram using data available from here. I'm using using the CSV version of this database to display the number of exoplantes discovered per year. A simple script would be
bulkdata <- read.csv('file.csv',head=1,sep=',')
pdf(file="yearcount.pdf",family="Times")
bins <- seq(min(bulkdata$discovered,na.rm=T),max(bulkdata$discovered,na.rm=T),by=1)
hist(bulkdata$discovered,breaks=bins,col='gray',ylab="Discovered",xlab="Year",main="",ylim=c(0,100),axes=FALSE)
axis(1, at=seq(1989,2012,by=1))
axis(2, at=seq(0,100,by=10))
grid(nx=10)
hist(bulkdata$discovered,breaks=bins,col='gray',ylab="Discovered",xlab="Year",main="", add=TRUE)
dev.off()
The problem is that the xaxis is not aligned with the 0 point of the yaxis. This is a problem because the lines drawn by grid() does not mean anything because they are not aligned with the ticks! I tried to add in axis(1, at=seq(1989,2012,by=1)) the option line=-1 to correct but this way the axis is correctly drawn but the grid start below the axis. Maybe a non standard package is needed?
?grid says:
If more fine tuning is required, use ‘abline(h = ., v = .)’
directly.
So here's a suggestion:
par(las=1,bty="l")
h <- hist(bulkdata$discovered,breaks=bins,
col='gray',ylab="Discovered",xlab="Year",main="",
ylim=c(0,100),axes=FALSE)
yrs <- 1989:2012
yvals <- seq(0,100,by=10)
axis(1, at=yrs)
axis(2, at=yvals)
abline(h=yvals,v=yrs,col="gray",lty=3)
hist(bulkdata$discovered,breaks=bins,
col='gray',ylab="Discovered",xlab="Year",main="", add=TRUE)
I would consider making the grid lines a little bit sparser (e.g. every 5 years?)