logo
down
shadow

ggplot2 - how to assign geom_text with arrow icon to second yaxis scale


ggplot2 - how to assign geom_text with arrow icon to second yaxis scale

By : user2174070
Date : October 19 2020, 08:10 AM
I think the issue was by ths following , We can achieve what you're after if we scale values of ws such that they use the same range as conc, and then apply the inverse transformation inside sec_axis. The transformation that we are applying takes the form y = a + b * x, where y are the conc and x the ws measurements. The two scaling coefficients a and b are then obtained by solving a system of two linear equations:
code :
# Calculate scaling coefficients a and b
y1 <- min(mydf$conc)
y2 <- max(mydf$conc)
x1 <- min(mydf$ws)
x2 <- max(mydf$ws)
b <- (y2 - y1) / (x2 - x1)
a <- y1 - b * x1
library(tidyverse)
mydf %>%
    mutate(ws.scaled = a + b * ws) %>%
    ggplot(aes(x = hour, y = conc)) +
        geom_line(color = "black") +
        geom_text(aes(x = hour, y = ws.scaled, angle = -wd + 90), label = "←", colour = "blue") +
        scale_x_continuous(breaks = seq(0, 24, by=6), limits=c(0,24), name="Hour") +
        scale_y_continuous(
            breaks = seq(0,30,10),
            name=  "Concentration",
            sec.axis = sec_axis(~ (. - a) / b, name = "Wind Speed (m/s)")) +
            theme(
                axis.title.y = element_text(color = "black"),
                axis.title.y.right = element_text(color = "black"))


Share : facebook icon twitter icon
scale bar and north arrow on map-ggplot2

scale bar and north arrow on map-ggplot2


By : user5945547
Date : March 29 2020, 07:55 AM
will help you A few years back I produced some code that could draw a scalebar (see also this post on r-sig-geo), this is the code I wrote back then. You could give it a go:
First some support functions:
code :
makeNiceNumber = function(num, num.pretty = 1) {
   # Rounding provided by code from Maarten Plieger
   return((round(num/10^(round(log10(num))-1))*(10^(round(log10(num))-1))))
}

createBoxPolygon = function(llcorner, width, height) {
   relativeCoords = data.frame(c(0, 0, width, width, 0), c(0, height, height, 0, 0))
   names(relativeCoords) = names(llcorner)
   return(t(apply(relativeCoords, 1, function(x) llcorner + x)))
}
addScaleBar = function(ggplot_obj, spatial_obj, attribute, addParams = 
list()) {
   addParamsDefaults = list(noBins = 5, xname = "x", yname = "y", unit = "m", 
        placement = "bottomright", sbLengthPct = 0.3, sbHeightvsWidth = 1/14)
   addParams = modifyList(addParamsDefaults, addParams)

   range_x = max(spatial_obj[[addParams[["xname"]]]]) - min(spatial_obj[[addParams[["xname"]]]])
   range_y = max(spatial_obj[[addParams[["yname"]]]]) -  min(spatial_obj[[addParams[["yname"]]]])
   lengthScalebar = addParams[["sbLengthPct"]] * range_x
   ## OPTION: use pretty() instead
   widthBin = makeNiceNumber(lengthScalebar / addParams[["noBins"]])
   heightBin = lengthScalebar * addParams[["sbHeightvsWidth"]]
   lowerLeftCornerScaleBar = c(x = max(spatial_obj[[addParams[["xname"]]]]) - (widthBin * addParams[["noBins"]]), y = min(spatial_obj[[addParams[["yname"]]]]))
   scaleBarPolygon = do.call("rbind", lapply(0:(addParams[["noBins"]] - 1), function(n) {
     dum = data.frame(createBoxPolygon(lowerLeftCornerScaleBar + c((n * widthBin), 0), widthBin, heightBin))
     if(!(n + 1) %% 2 == 0) dum$cat = "odd" else dum$cat = "even"
     return(dum)
   }))
   scaleBarPolygon[[attribute]] = min(spatial_obj[[attribute]])
   textScaleBar = data.frame(x = lowerLeftCornerScaleBar[[addParams[["xname"]]]] + (c(0:(addParams[["noBins"]])) * widthBin), y = lowerLeftCornerScaleBar[[addParams[["yname"]]]],
                             label = as.character(0:(addParams[["noBins"]]) * widthBin))
   textScaleBar[[attribute]] = min(spatial_obj[[attribute]])

   return(ggplot_obj +
     geom_polygon(data = subset(scaleBarPolygon, cat == "odd"), fill = "black", color = "black", legend = FALSE) +
     geom_polygon(data = subset(scaleBarPolygon, cat == "even"), fill = "white", color = "black", legend = FALSE) +
     geom_text(aes(label = label), color = "black", size = 6, data = textScaleBar, hjust = 0.5, vjust = 1.2, legend = FALSE))
}
library(ggplot2)
library(sp)

data(meuse)
data(meuse.grid)
ggobj = ggplot(aes(x = x, y = y, color = zinc), data = meuse) + geom_point()
# Make sure to increase the graphic device a bit
addScaleBar(ggobj, meuse, "zinc", addParams = list(noBins = 5))
assign a list of colour to the geom_text in ggplot2

assign a list of colour to the geom_text in ggplot2


By : user2811111
Date : March 29 2020, 07:55 AM
I think the issue was by ths following , plot with assigned colors. , Try this minor change to the geom_text call:
code :
#plot 
p <- ggplot(mtcars, aes(x=wt, y=mpg, label=rownames(mtcars)))
p + geom_text(colour=tmpC)
p + geom_text(colour=rep(c('red','purple'), length.out = nrow(mtcars)))
Define yAxis value with two different yAxis scale highcharts

Define yAxis value with two different yAxis scale highcharts


By : David Doan
Date : March 29 2020, 07:55 AM
I hope this helps . You should set alignTicks as false
Conditionally assign geom_text placement for bar charts with ggplot2

Conditionally assign geom_text placement for bar charts with ggplot2


By : user3060677
Date : March 29 2020, 07:55 AM
seems to work fine I am having an issue when making bar charts with mixed sign values in ggplot2. Take the following example:
code :
df <- data.frame(year = letters[1:3],
                 value = c(1, -1,-5)) %>%
    mutate(text_location = ifelse(value < 0,0,value))

ggplot(df, aes(year, value)) +
    geom_col() +
    geom_text(aes(y = text_location,label = value), vjust = 0.0, size = 5)

Can't plot a scale bar or north arrow on ggplot2

Can't plot a scale bar or north arrow on ggplot2


By : Michael Z
Date : March 29 2020, 07:55 AM
I wish this help you The ggsn package is useful here. Without the GPS data, I can't execute all of your script, but this should add the north symbol and scale bar in reasonable locations, given the specified x and y limits.
Related Posts Related Posts :
  • Authentication failure with rdrop2
  • DT data table display error
  • Issue when adding new rows (with nested dataframes within) to a dataframe
  • R-How to compare two dataframe and update list column value
  • Series vector for approximating pi
  • what is difference between "variance explained " in Random Forest and "merror" in XGBoost
  • R - Cast dataframe on unique rows - reshape2
  • ggplot2: plot correct proportions using geom_bar
  • Speedup query for R data.table - can this two-argument function be applied by group more quickly?
  • apply a function to several columns at once with mutate
  • R 'cowplot' neatly produce gridded plot with shared (common) legends and unique legends
  • Repeat R script for many times and save results to text file
  • How to negative lookbehind for special characters
  • data.table inner join produces error when no match is found
  • Create a new column base on existing column, but row above
  • Is there a way to visualize the process of source() in RStudio?
  • google places api consumes 10 request but I am doing only 1
  • Statistical mode of a categorical variable in R (using mlv)
  • Using for-loop to mutate a data.frame in r
  • Make plot with regression line for mixed model
  • Shortcut to select matces cases in R studio
  • vectoriced norm/matrix multiplication
  • Negative log10 transformation in R
  • Plot data with duplicate points
  • Visualizing crosstab tables with a plot in R - changing colours
  • How to manually modify automated numbers and labels in plot
  • How can I follow any redirections of a url in R?
  • Add jitter to box plot using markers in plotly
  • Adding an extra item to the legend
  • ggplot fills in data in the wrong order
  • Convert list to data frame
  • R: filtering by list(s) of strings and returning all results that start with the content of the lists
  • R:How to attach parts of a data frame with different headers and/or an overflowing piece of the dat frame
  • How to use 'par' for manipulating plot margins?
  • Can dplyr::case_when return mix of NAs and non-NAs?
  • Text preprocessing and topic modelling using text2vec package
  • Uploading multiple files in Shiny, process the files, rbind the results and return a download
  • R levelplot: color green-white-red (white on 0) according to one variable, but show the values of another variable
  • Why [i] doesn't point to the starting point in a vector
  • In R after generating a mvrnorm distribution, Y, what does Y[,1] do?
  • expand a data frame to have as many rows as range of two columns in original row
  • Getting started with R and CFA
  • Re order x-axis in ggplot so time goes from 12AM to 11PM in R
  • R - Automatically stack every nth column of a data frame and save them as new objects
  • How to format dplyr output in R into doubles (or other workable format)?
  • Dataframe to matrix conversion using tapply turns zeros to NAs
  • Smallest multiple of 1:20 - How can I make it quicker?
  • How to specify the size of a graph in ggplot2 independent of axis labels
  • How can I find the number of a vector's elements in another vector?
  • ROC curve from train/test set in caret R package
  • Random Forest for a mixture of categorical,numeric and "unwanted" variables which include missing values
  • extract certain data from multiple excel files with R
  • Matrix with counts of wins and losses between methods in R
  • Grouping string variables from a dataframe by best string match to make subsets
  • Reorder does not work after adding second geom_points
  • cover POS data formate to the one can apply Arules (Apriori)
  • Matching values between data frames based on overlapping dates
  • Grouped bar chart turns into stacked bar chart ggplot
  • R: How to fill in NA Values within a Column based on grouping?
  • Two action buttons, but only the first one, that is written in the server file, works?
  • shadow
    Privacy Policy - Terms - Contact Us © voile276.org