I'm using Gadfly to plot layers, how can I change the order?
I already tried follow the docs but it doesn't work.
using DataFrames
df = readtable("data/01_heights_weights_genders.csv")
xmin, xmax = extrema(df[:Height])
ymin, ymax = extrema(df[:Weight])
plot(layer(df, x="Height", y="Weight", Geom.point, color="Gender", order = 1),
layer(x=[xmin, xmax],y=[ymin, ymax], Geom.point,Geom.line, Theme(default_color=colorant"purple"), order = 10))
Solved with
plot(df,layer(x="Height", y="Weight", Geom.smooth(method=:lm,smoothing=0.2), Theme(default_color=colorant"red")),
layer(x="Height", y="Weight", Geom.point))
Related
I am trying to plot the below chart:
below is my attempt, colors and labels would be fine_tuned, just showing the problem here. Trying to be straight forward to with the second stat_function's x values limited to (0.28,0.30), whereas the first stat_function having a longer x values (0.28, 0.32).
library(tidyverse)
theme_set(theme_light())
alpha_single <- 3850
beta_single <- 8818
ggplot(data.frame(x=c(0.28,0.32)), aes(x))+
stat_function(fun = dbeta, args = list(shape1 = alpha_single, shape2 = beta_single))+
stat_function(data = data.frame(x=c(0.28,0.3)), aes(x),fun = dbeta, args = list(shape1 = alpha_single, shape2 = beta_single), geom = "area", fill = "blue", inherit.aes = F)
Created on 2019-09-19 by the reprex package (v0.3.0.9000)
Not sure how ggplot interpreted this. Any pointer would be appreciated.
Grateful if anyone can show me how do what I intended with stat_function. That would help me finally understand how stat_function works. I believe I can do this with a more iterative approach, where I would generate data.frame(s) and plot them with different geom(s). but just to understand why this more straightforward way wouldn't work? how come the blue just filled everything?
I am new to R, and I am trying to do what it seems to be the simplest thing, but for the love of god, I cannot find out how to do it!
As the title says, I want to plot x=1, y=1 and y=1/(2*x), preferably with different colors, and after that, I want to paint the area between the x,y axis and the lines ploted. Something like this:
Thanks in advance
There are various ways to do this. For example, using library(ggplot2) you can do
# define how far beyond the intersection we calculate curve values
xmax = 1.1
xmin = 1/(2*xmax)
# calculate coordinates of the curve
x = seq(xmin, xmax, length.out = 100)
y = 1/(2*x)
# create polygon coordinates that follow the curve and ...
# ...extend down the staight lines to infinity
poly = data.frame(
x = c(x[x<1 & y<1], 1, 1, -Inf, -Inf, 0.5),
y = c(y[x<1 & y<1], 0.5, -Inf, -Inf, 1, 1))
ggplot(data.frame(x,y), aes(x,y)) +
geom_polygon(data = poly, fill='yellow') +
geom_line() +
geom_hline(aes(yintercept=1)) +
geom_vline(aes(xintercept=1)) +
coord_equal(1, c(0,1), c(0,1))
This is a follow-on to a previous question about getting some custom error bars.
The look of the plot is how I need it, so don't worry about commenting in solely in regards to that (happy to hear opinions attached to other help though)
Because these plots are generated in a loop, and the error bars are actually only added if a condition is met, I cant simply merge all the data up front, so assume for the purpose of this exercise the plot data and errorbar data are from different dfs.
I have a ggplot, to which I attempt to add some error bars using a different dataframe. When I call the plot, it says that it cannot find the y values from the parent plot, even though I'm just trying to add error bars using new data. I know this has to be a syntax error but I am stumped...
First lets generate data and the plot
library(ggplot2)
library(scales)
# some data
data.2015 = data.frame(score = c(-50,20,15,-40,-10,60),
area = c("first","second","third","first","second","third"),
group = c("Findings","Findings","Findings","Benchmark","Benchmark","Benchmark"))
data.2014 = data.frame(score = c(-30,40,-15),
area = c("first","second","third"),
group = c("Findings","Findings","Findings"))
# breaks and limits
breaks.major = c(-60,-40,-22.5,-10, 0,10, 22.5, 40, 60)
breaks.minor = c(-50,-30,-15,-5,0, 5, 15,30,50)
limits =c(-70,70)
# plot 2015 data
ggplot(data.2015, aes(x = area, y = score, fill = group)) +
geom_bar(stat = "identity", position = position_dodge(width = 0.9)) +
coord_flip() +
scale_y_continuous(limit = limits, oob = squish, minor_breaks = breaks.minor,
breaks = breaks.major)
Calling the plot (c) produces a nice plot as expected, now lets set up the error bars and attempt to add them as a new layer in the plot "c"
# get the error bar values
alldat = merge(data.2015, data.2014, all = TRUE, by = c("area", "group"),
suffixes = c(".2015", ".2014"))
alldat$plotscore = with(alldat, ifelse(is.na(score.2014), NA, score.2015))
alldat$direction = with(alldat, ifelse(score.2015 < score.2014, "dec", "inc"))
alldat$direction[is.na(alldat$score.2014)] = "absent"
#add error bars to original plot
c <- c+
geom_errorbar(data=alldat, aes(ymin = plotscore, ymax = score.2014, color = direction),
position = position_dodge(width = .9), lwd = 1.5, show.legend = FALSE)
When I call c now, I get
"Error in eval(expr, envir, enclos) : object 'score' not found"
Why does it look for data.2015$score when I just want it to overlay the geom_errorbar using the second alldat dataframe?
EDIT* I've tried to specify the ymin/ymax values for the error bars using alldata$plotscore and alldat$score.2014 (which I am sure is bad practice), it plots, but the bars are in the wrong positions/out of order with the plot (e.g. swapped around, on the benchmark bars instead, etc.)
In my experience, this error about some variable not being found tells me that R went to look in a data.frame for a variable and it wasn't there. Sometimes the solution is as simple as fixing a typo, but in your case the score variable isn't in the dataset you used to make your error bars.
names(alldat)
[1] "area" "group" "score.2015" "score.2014" "plotscore" "direction"
The y variable is a required aesthetic for geom_errorbar. Because you set a y variable globally within ggplot, the other geoms inherit the global y unless you specifically map it to a different variable. In the current dataset, you'll need map y to the 2015 score variable.
geom_errorbar(data=alldat, aes(y = score.2015, ymin = plotscore,
ymax = score.2014, color = direction),
position = position_dodge(width = .9), lwd = 1.5, show.legend = FALSE)
In your comment you indicated you also had to add fill to geom_errobar, as well, but I didn't find that necessary when I ran the code (you can see above that group is a variable in the second dataset in the example you give).
The other option would be to make sure the 2015 score variable is still named score after merging. This can be done by changing the suffixes argument in in merge. Then score will be in the second dataset and you won't have to set your y variable in geom_errorbar.
alldat2 = merge(data.2015, data.2014, all = TRUE, by = c("area", "group"),
suffixes = c("", ".2014"))
...
names(alldat2)
[1] "area" "group" "score" "score.2014" "plotscore" "direction"
I have been playing around with ggplot2 a bunch and found Adding table within the plotting region of a ggplot in r
I was wondering is there any method for this for plotting using non cartesian coordinates, eg if map coordinates were used for the positioning of the table. I had some maps and thought it would be cool if they could have their corresponding data in a table for points to show more detail.
If anyone knows a work around for annotation_custom for non cartesian coordinates it would be greatly appreciated.
EDIT:Here is a image of what my map looks like, I was just thinking is there another way to plot the table on the left side of this.
EDIT: here is what Im attempting to do
EDIT: Here is the basic code structure for the plot
library(ggplot2)
library(ggmap)
plotdata <- read.csv("WellSummary_All_SE_NRM.csv", header = T)
plotdata <- na.omit(plotdata)
plotdata <- plotdata[1:20, c("Unit_No","neg_decimal_lat", "decimal_long", "max_drill_depth", "max_drill_date")]
map.plot<- get_map(location = c(min(plotdata$decimal_long),
min(plotdata$neg_decimal_lat),
max(plotdata$decimal_long),
max(plotdata$neg_decimal_lat)),
maptype ="hybrid",source = "google", zoom=8)
theme_set(theme_bw(base_size = 8))
colormap <- c("darkblue","blue","lightblue", "green", "yellow", "orange","darkorange", "red", "darkred")
myBreaks <- c(0,2, 10, 50, 250, 1250, 2000, 2500)
static.map <- ggmap(map.plot) %+% plotdata +
aes(x = decimal_long,
y = neg_decimal_lat,
z= max_drill_depth)+
stat_summary2d(fun = median, binwidth = c(.03, .03),alpha = 0.7) +
scale_fill_gradientn(name = "depth", colours= colormap, breaks=myBreaks,labels = format(myBreaks),
limits= c(0,2600), space = "Lab") +
labs(x = "Longitude",y = "Latitude")+
geom_text(aes(label=Unit_No),hjust=0, vjust=0,size=2,
position = position_dodge(width=0.9), angle = 45)+
coord_map()
#Creates image of the plot in file to Working Directory
filename=paste("2dmap",".png", sep="")
cat("\t",filename,"file created, saving...\n")
print(static.map)
cat("\tpassed mapping, file now being made\n")
ggsave(filename=filename,
plot = static.map,
scale = 1,
width = 6, height = 4,
dpi = 300)
I will try to upload the data today, cheers for some of the pointers already!
I have uploaded the data, dont worry about the positioning of the gradient values and text tags as I can fix them later I will also link the current ggmap code but I am using a very large loop for the data to be sorted.
https://drive.google.com/file/d/0B8qOIJ-nPp9rM1U1dkEzMUM0Znc/edit?usp=sharing
try this,
library(gridExtra)
grid.arrange(tableGrob(head(iris)), qplot(1,1), ncol=2)
annotation_custom wouldn't help, it's meant for adding things inside the plot panel, not to the side.
I am trying to plot a specific region in the arctic with ggmap. The center of the region is somewhere around lat. 80 lon. 0, unfortunately only a grey background and the latitude and longitude axis are shown. I tried to plot different regions and my code seems to work on every location, except regions which are beyond lat. 73.6. Here is an example of my code:
library(ggmap)
library(mapproj)
location <- get_map(location = c(lon = 0, lat = 80), zoom = 4, maptype = "hybrid")
ggmap(location)
So does anyone know, why ggmap is unable to plot this location?
I had the same problem (when trying to plot Antartica) and to get around it, I resorted to ggplot, but relying on a couple of functions from the ggmap package.
As #Henrik's link suggests, the map projection seems to be the problem.
The entire idea and code is courtesy of David Kahle
Here's what you can do to get it to work for your case:
location <- get_map(location = c(lon = 0, lat = 80), zoom = 4, maptype = "hybrid")
#Create a small data frame to pass to ggplot
fourCorners <- expand.grid(
lon = as.numeric(attr(location, "bb")[, c("ll.lon", "ur.lon")]),
lat = as.numeric(attr(location, "bb")[, c("ll.lat", "ur.lat")])
)
# The inset_raster function needs 4 data coordinates. Pull it out of your "location" that you got via get_map
xmin <- attr(location, "bb")$ll.lon
xmax <- attr(location, "bb")$ur.lon
ymin <- attr(location, "bb")$ll.lat
ymax <- attr(location, "bb")$ur.lat
# Now you are ready to plot it
mp <- ggplot(fourCorners, aes(x = lon, y = lat) ) +
inset_raster(location, xmin, xmax, ymin, ymax)
mp
Which gives you your "hybrid" map, centered at (Longitude=0, lat=80)