logo
down
shadow

apply transparent background to divide plot area based on x values using ggplot


apply transparent background to divide plot area based on x values using ggplot

Content Index :

apply transparent background to divide plot area based on x values using ggplot
Tag : r , By : Noah
Date : November 29 2020, 04:01 AM

I hope this helps you . I think you want something like this. You'll have to designate groups and fill by that group in your geom_ribbon, and set your ymin and ymax as you like.
library(tidyverse)
    mtcars$group <- ifelse(mtcars$wt <= 3.5, "<= 3.5", "> 3.5")
mtcars <- arrange(mtcars, wt)
mtcars$group2 <- rleid(mtcars$group)
mtcars_plot <- head(do.call(rbind, by(mtcars, mtcars$group2, rbind, NA)), -1)
mtcars_plot[,c("group2","group")] <- lapply(mtcars_plot[,c("group2","group")], na.locf)
mtcars_plot[] <- lapply(mtcars_plot, na.locf, fromLast = TRUE)

ggplot(mtcars_plot, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_smooth(aes(), method=lm, se=F, fullrange=TRUE) +
  geom_ribbon(aes(ymin = mpg *.75, ymax = mpg * 1.25, fill = group), alpha = .25) +
  labs(fill = "Weight Class")
mtmodel <- lm(mpg ~ wt, data = mtcars)
mtcars$Low <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,2]
mtcars$High <- predict(mtmodel, newdata = mtcars, interval = "confidence")[,3]
ggplot(mtcars_plot, aes(x = wt, y = mpg)) +
  geom_point() +
  geom_smooth(aes(), method=lm, se=F, fullrange=TRUE) +
  geom_ribbon(aes(ymin = Low, ymax = High, fill = group), alpha = .25) +
  labs(fill = "Weight Class") +
  scale_fill_manual(values = c("red", "orange"), name = "fill")

Comments
No Comments Right Now !

Boards Message :
You Must Login Or Sign Up to Add Your Comments .

Share : facebook icon twitter icon

R: change background color of plot for specific area only (based on x-values)


Tag : r , By : mtnmuncher
Date : March 29 2020, 07:55 AM
To fix the issue you can do This can be achieved by thinking about the plot somewhat differently to your description. Basically, you want to draw a coloured rectangle between the desired positions on the x-axis, filling the entire y-axis limit range. This can be achieved using rect(), and note how, in the example below, I grab the user (usr) coordinates of the current plot to give me the limits on the y-axis and that we draw beyond these limits to ensure the full range is covered in the plot.
plot(1:10, 1:10, type = "n", axes = FALSE) ## no axes
lim <- par("usr")
rect(2, lim[3]-1, 4, lim[4]+1, border = "red", col = "red")
axis(1) ## add axes back
axis(2)
box()   ## and the plot frame
X <- c(1,3)
Y <- c(2,4)
plot(1:10, 1:10, type = "n", axes = FALSE) ## no axes
lim <- par("usr")
rect(X[1], Y[1], X[2], Y[2], border = "red", col = "red")
axis(1) ## add axes back
axis(2)
box()   ## and the plot frame
botleft <- c(1,2)
topright <- c(3,4)
plot(1:10, 1:10, type = "n", axes = FALSE) ## no axes
lim <- par("usr")
rect(botleft[1], botleft[2], topright[1], topright[2], border = "red",
     col = "red")
axis(1) ## add axes back
axis(2)
box()   ## and the plot frame

Google polygonal map background color transparent, surrounding area semi-transparent overlay


Tag : development , By : phil
Date : March 29 2020, 07:55 AM
I wish did fix the issue. Using some CSS and a large 512 x 512px png I have managed to emulate what I wanted to achieve. I'm sure there would be more accurate methods but this has worked for me.
http://www.syn-rg.com.au/Development/United-Energy/mg_map/MG_Area_map_02.html
<!DOCTYPE html>
<html>
  <head>
    <meta name="viewport" content="initial-scale=1.0, user-scalable=no" />
    <style type="text/css">
      html { height: 100% }
      body { height: 100%; margin: 0; padding: 0; }
      #map_canvas {
    background-color: #EAEAEA;
    border: 1px solid #CCCCCC;
    height: 400px;
    margin-bottom: 10px;
    margin-left: auto;
    margin-right: auto;
    width: 532px;
}
#map_canvas div div div div div img{ border:1000px solid black;margin:-1000px -1000px;}
/*#map_canvas div div div div div div div{ background: none repeat scroll 0px 0px rgba(0, 0, 0, 0.5);}*/
    </style>
    <script type="text/javascript" src="http://maps.googleapis.com/maps/api/js?key=AIzaSyA7UaoyrY4KyoW1iEU0KFo0ZOxH5w30oZ8&sensor=true"></script>
    <script type="text/javascript">
var overlay;
USGSOverlay.prototype = new google.maps.OverlayView();

function initialize() {
    var myLatLng = new google.maps.LatLng(-37.815676, 145.449005);
    var myOptions = {
        zoom: 9,
        center: myLatLng,
        mapTypeId: google.maps.MapTypeId.ROADMAP
    };
    var map = new google.maps.Map(document.getElementById("map_canvas"), myOptions);
    var swBound = new google.maps.LatLng(-38.269876, 144.842405); // Latitude, Longitude = 182.749 or 107.183 or 108.4443 or 107.77615
    var neBound = new google.maps.LatLng(-37.161476, 146.249005); //  -0.5542, +0.7033 = 256px
    //var swBound = new google.maps.LatLng(-37.783, 144.966); 
    //var neBound = new google.maps.LatLng(-37.225, 145.66930); 
    //var swBound = new google.maps.LatLng(62.281819, -150.287132);
    //var neBound = new google.maps.LatLng(62.400471, -150.005608);
    var bounds = new google.maps.LatLngBounds(swBound, neBound);
    // Photograph courtesy of the U.S. Geological Survey
    var srcImage = 'images/mg_map_full.png';
    overlay = new USGSOverlay(bounds, srcImage, map);
}

function USGSOverlay(bounds, image, map) {
    // Now initialize all properties.
    this.bounds_ = bounds;
    this.image_ = image;
    this.map_ = map;
    // We define a property to hold the image's div. We'll
    // actually create this div upon receipt of the onAdd()
    // method so we'll leave it null for now.
    this.div_ = null;
    // Explicitly call setMap on this overlay
    this.setMap(map);
}
USGSOverlay.prototype.onAdd = function () {
    // Note: an overlay's receipt of onAdd() indicates that
    // the map's panes are now available for attaching
    // the overlay to the map via the DOM.
    // Create the DIV and set some basic attributes.
    var div = document.createElement('div');
    div.style.borderStyle = "none";
    div.style.borderWidth = "0";
    div.style.borderColor = "red";
    div.style.position = "absolute";
    div.style.opacity = "0.3";
    // Create an IMG element and attach it to the DIV.
    var img = document.createElement("img");
    img.src = this.image_;
    img.style.width = "100%";
    img.style.height = "100%";
    img.style.position = 'absolute';
    div.appendChild(img);
    // Set the overlay's div_ property to this DIV
    this.div_ = div;
    // We add an overlay to a map via one of the map's panes.
    // We'll add this overlay to the overlayImage pane.
    var panes = this.getPanes();
    panes.overlayImage.appendChild(div);
}
USGSOverlay.prototype.draw = function () {
    // Size and position the overlay. We use a southwest and northeast
    // position of the overlay to peg it to the correct position and size.
    // We need to retrieve the projection from this overlay to do this.
    var overlayProjection = this.getProjection();
    // Retrieve the southwest and northeast coordinates of this overlay
    // in latlngs and convert them to pixels coordinates.
    // We'll use these coordinates to resize the DIV.
    var sw = overlayProjection.fromLatLngToDivPixel(this.bounds_.getSouthWest());
    var ne = overlayProjection.fromLatLngToDivPixel(this.bounds_.getNorthEast());
    // Resize the image's DIV to fit the indicated dimensions.
    var div = this.div_;
    div.style.left = sw.x + 'px';
    div.style.top = ne.y + 'px';
    div.style.width = (ne.x - sw.x) + 'px';
    div.style.height = (sw.y - ne.y) + 'px';
}
USGSOverlay.prototype.onRemove = function () {
    this.div_.parentNode.removeChild(this.div_);
    this.div_ = null;
}
    </script>
  </head>
  <body onload="initialize()">
    <div id="map_canvas" style="position: relative; background-color: rgb(229, 227, 223); overflow: hidden;"></div>
  </body>
</html>

Grouped bar plot in ggplot with y values based on combination of 2 categorical variables?


Tag : r , By : Thierry Brunet
Date : March 29 2020, 07:55 AM
may help you . I think you are looking for the interaction() (i.e. get all unique pairings) between df$Verb_Type and df$speaker to get the column groupings you are after. You can pass this directly to ggplot or make a new variable ahead of time:
ggplot(df, aes(x = Frame, y = proportion_type,
               group = interaction(Verb_Type, speaker), fill = Verb_Type, alpha = speaker)) +
    geom_bar(stat = "identity", position = "dodge") +
    scale_alpha_manual(values = c(.5, 1))
df$grouper <- interaction(df$Verb_Type, df$speaker)
ggplot(df, aes(x = Frame, y = proportion_type,
               group = grouper, fill = Verb_Type, alpha = speaker)) +
    geom_bar(stat = "identity", position = "dodge") +
    scale_alpha_manual(values = c(.5, 1))

How to save the plot with the labels and ticks area transparent but not the main plot area in matplotlib?


Tag : python , By : Mostapen
Date : March 29 2020, 07:55 AM
Does that help There is a bug in the newest version of matplotlib. I'm not sure if this applies to here, because you do not state which version you are using.
The workaround would be to use a transparent facecolor and leave the other arguments at their defaults.
fig.savefig("fname", facecolor=(1,1,1,0))

Increasing the plot area in ggplot to cope with geom_text at plot edges


Tag : r , By : xie renhui
Date : March 29 2020, 07:55 AM
Related Posts Related QUESTIONS :
  • reshape wide to long based on part of column name
  • How to get a hyperlink for the words in a description in an r dataframe?
  • shinymeta works locally but breaks when published to shinyapps.io
  • Deparse and (un)escape quotes
  • Regression table with clustered standard errors in R jupyter notebook?
  • Disaggregate quarterly data to daily data in R keeping values?
  • How to save output to console and file simultaneously in RStudio server?
  • Why does data.table j have a different environment when directly calling mget() vs calling mget() inside another functio
  • scale_fill_viridis_c color bar on a log scale
  • How to change the lab name corresponding to function in ggplot
  • R, filtering for an element in a list in a dataframe cell
  • Extracting only bottom temperature from 4d NetCDF file
  • How to add/wrap lines of text to .tex with .sh script
  • R - building new variables from sequenced data
  • Sum rows values one after the other
  • Nesting ifelse inside summarytools
  • How best to divide different levels of a factor by one another in dataframe in R?
  • Why does my code run multiple times before I type data into the table? How do I make an action button that creates a tab
  • How to impute missing values not at random?
  • Set the y limits of an added average line of a plotly plot
  • how to calculate a new column after grouping with dplyr
  • Extract data from rows creating new columns using R
  • Create a filled area line plot with plotly
  • When do I need parentheses around an if statement to control the sequence of a formula in R?
  • my graph in ggplot2 contains an "e" character in y-axis
  • Making variables immutable in R
  • R: Difference between the subsequent ranks of a item group by date
  • Match data within multiple time-frames with dplyr
  • Conditional manipulation and extension of rows in data.table also considering previous extensions without for-loop
  • Conditional formula referring to preview row in DF not working
  • Set hoverinfo text in plotly scatterplot
  • Histogram of Sums from Categorical/Binary Data
  • Efficiently find set differences and generate random sample
  • Find closest points from data set B to point in data set A, using lat long in R
  • dplyr join on column A OR column B
  • Replace all string if row starts with (within a column)
  • Is there a possibility to combine position_stack and nudge_x in a stacked bar chart in ggplot2?
  • How can I extract bounding boxes in a row-wise manner using R?
  • How do I easily sum up values in different columns?
  • Reading numeric Date value from CSV file to data.frame in "R"
  • R programming: creating a stacked bar graph, with variable colors for each stacked bar
  • How to identify all columns that contain binary representation
  • Filter different groups by different factor levels
  • Saving .xlsx file to disc, form http post request
  • Add an "all" option under the filter that selects the number of rows displayed in a datatable
  • How to select second column of every xts in list
  • Generate a frequency dataframe out of an input dataframe
  • Why manual autocorrelation does not match acf() results?
  • Merge 3 dataframes which are different to each other
  • remove adjacent duplicates from string
  • How to change the position of stacked stacked bar chart in ggplot in R?
  • How to divide each of a range a variables by a second range of variables in R
  • Why do I need to assemble vector before scaling in Spark?
  • How to select individuals which appear in multiple groups?
  • How can I fill columns based on values in another column?
  • 32 bit R and 64 bit R: output differs
  • Remove a single backslash in paste0 output
  • ggplot2 different label for the first break
  • TSP in R, with given distances
  • How to find the given value from the range of values?
  • shadow
    Privacy Policy - Terms - Contact Us © scrbit.com