Color grid lines in Julia - plot

I would like to color the grid lines in a plot. Here is some reproducible code:
using Plots
Plots.plot(rand(10))
Output:
Imagine I want to have green grid lines, how can we change the color of grid lines in Julia? I check the docs, but I can only find attributes like alpha, line width and style and not the color.

Here is some code to get the green grid:
plt = Plots.plot(rand(10))
xaxis = Plots.get_axis(Plots.get_subplot(plt,1),:x)
yaxis = Plots.get_axis(Plots.get_subplot(plt,1),:y)
xaxis[:gridalpha] = 0.6
yaxis[:gridalpha] = 0.6
xaxis[:foreground_color_grid] = colorant"green"
yaxis[:foreground_color_grid] = colorant"green"
plt
Many other attributes are described in the docs page you linked to.

Related

Highlight a Specific Section of a Treemap using Treemap package in R

I am using the Treemap package in R to highlight the number of COVID outbreaks in different settings. I am making a number of different reports using R Markdown. Each one describes a different type of settings and I would like to highlight that setting in the treemap for each report, showing what proportion of total outbreaks occur in the setting in question. For example you I am currently working on the K-12 school report and would like to highlight the box representing that category in the figure.
I was previously using an exploded donut pie chart however there were two many subcategories and the graph became hard to read.
I am picturing a way to change the label or border on one specific box, ie. put a yellow border around the box or make the label yellow. I found a way to do both these things for all the boxes but not just one specific box. I made this image using the snipping tool to further illustrate what the desired outcome might look like. The code to generate the treemap can be found in the link below. It looks like this:
# library
library(treemap)
# Build Dataset
group <- c(rep("group-1",4),rep("group-2",2),rep("group-3",3))
subgroup <- paste("subgroup" , c(1,2,3,4,1,2,1,2,3), sep="-")
value <- c(13,5,22,12,11,7,3,1,23)
data <- data.frame(group,subgroup,value)
# treemap
treemap(data,
index=c("group","subgroup"),
vSize="value",
type="index"
)
This is the most straightforward information I can find about the package, this is where I took the sample image and code from: https://www.r-graph-gallery.com/236-custom-your-treemap.html
It looks like the treemap package doesn't have a built-in way to do this. But we can hack it by using the data frame returned by treemap() and adding a rectangle to the appropriate viewport.
# Plot the treemap and save the data used for plotting.
t = treemap(data,
index = c("group", "subgroup"),
vSize = "value",
type = "index"
)
# Add a rectangle around subgroup-2.
library(grid)
library(dplyr)
with(
# t$tm is a data frame with one row per rectangle. Filter to the group we
# want to highlight.
t$tm %>%
filter(group == "group-1",
subgroup == "subgroup-2"),
{
# Use grid.rect to add a rectangle on top of the treemap.
grid.rect(x = x0 + (w / 2),
y = y0 + (h / 2),
width = w,
height = h,
gp = gpar(col = "yellow", fill = NA, lwd = 4),
vp = "data")
}
)

How can I change a color of a surface in VineCopula::plot.BiCop function?

Do you know how I can change a color of a surface in VineCopula::plot.BiCop function? I've tried to use a col argument but it's worked just for color of lines of a grid.
library(VineCopula)
par.gauss<-BiCopTau2Par(1, .7, check.taus = TRUE)
obj.gauss <- BiCop(family = 1, par = par.gauss)
plot(obj.gauss,zlim=c(0,12))
I've tried:
plot(obj.gauss,zlim=c(0,12), col="green")
but it's changed just a color of lines.
You could use
n <- 70
plot(obj.gauss, zlim=c(0,12), col.regions=rainbow(n))
n gives the number of colors used in your plot. rainbow is a color palette, there are several others. Look at ?rainbow, you could use
hcl.colors(n)
rainbow(n)
heat.colors(n)
terrain.colors(n)
topo.colors(n)
cm.colors(n)
and there are several parameters, so for example
plot(obj.gauss, zlim=c(0,12), col.regions=rainbow(120, s=0.5, alpha=0.75))

How can i specify the color of a bar in a bar chart by its value?

Well, i created a bar chart and now i want to specify the color of a bar depending of its value on y-axis. simplified- if the value is positive the bar should be red and is the value nagative the bar should be blue.
For me it's only possible to change the color along the x-axis but not the y-axis.
from bokeh.palettes import plasma
source = ColumnDataSource(data={'date' : pd.to_datetime(df_data['date'], format='%Y-%m'), 'values' : df_data['values'], 'color' : plasma(256)})
p = figure(x_axis_label='time',
x_axis_type='datetime',
y_axis_label='diff',
tools = [hover]
toolbar_location=None
title="title")
p.vbar(x = 'date',top = 'values', source=source, width=timedelta(days=20), color = 'color')
I've found an example on:
https://docs.bokeh.org/en/latest/docs/user_guide/categorical.html
But i need to differentiate or to color the bars by their values no by their number. I know my example makes no sense, but i only want to demonstrate what my expectations are.
Ok, i found a solution by myself by unsing the cut function of pandas.
import pandas as pd
import numpy as np
values = array(df_data['values']).values)
bins = [np.NINF, 0, np.inf]
categories = pd.cut(values, bins, right=False)
palette = ['blue', 'red']
colors = []
for i in categories.codes:
colors.append[palette[i]]
# Now i can add this column to my ColumnDataSource:
source = ColumnDataSource(data={'date' : pd.to_datetime(df_data['date'], format='%Y-%m'), 'values' : df_data['values'], 'color' : colors}
p.vbar(x = 'date',top = 'values', source=source, width=timedelta(days=20), color = 'colors')
Of course this is just as "quick and dirty" solution and there is enough room for optimization.

r bokeh chart legend - placed poorly move

I have been working in flexdashboards using rbokeh to draw some dynamic graphs. Because this is a bar chart mapped to categorical data in the variable Classification, I am unable to manually create a legend, which is fine because rbokeh does it automatically.
However, I am having some issues with the legend and labeling:
It is placed horribly, I would like to tell r to place in the upper left hand corner to get it away from bars with content.
I would like to drop the red ab_line into the legend and label it (using standard legend = will not work because of the mapped variables in the base chart
This graph needs to be 508 compliant for translation, the flexdashboard is, as well as the bokeh tools on the left hand margin and the keys in the pop ups, but the values and labels remain in English. Does anyone have a way of making the charts responsive to google translate? I am fine if that involves editing the extruded page....I will just need more guidance in doing it there.
figure(title=" Confirmed & Probable Cases by Year",width= 1400, height
=350)%>%
ly_bar(x=Year, y= count, position='stack', data=probConf,
width=.9,hover=TRUE, legend=TRUE, color=Classification) %>%
x_axis(label ='Year')%>%
y_axis(label ='Cases')%>%
ly_abline(v=17.5, legend=NULL, color = "red", width =1, alpha=.5)%>%
[![enter image description here][1]][1]set_palette(discrete_color = pal_color(c("#ee9f00", "#ffcc66")))
To answer number 1, you can use legend_location to specify the placement of the legend (see example below and note I replaced the probConf data with the lattice barley dataset so that it is reproducible for others).
figure(title = " Confirmed & Probable Cases by Year", width = 1400,
height = 350, legend_location = "top_left") %>%
ly_bar(x = variety, y = yield, position = "stack", data = lattice::barley,
width = 0.9, hover = TRUE, legend = TRUE, color = year) %>%
x_axis(label = "Year") %>%
y_axis(label = "Cases") %>%
ly_abline(v = "Svansota:1", color = "red", width = 1, alpha = 0.5) %>%
set_palette(discrete_color = pal_color(c("#ee9f00", "#ffcc66")))
#2 is currently difficult to achieve in rbokeh but it should be more robust to situations like this (mixing mapped and user-defined legend entries) in the future. If ly_abline() were to accept data as an argument, you could use use a mapped variable for color to resolve the issue.
One solution that isn't very pretty is to manually draw the bar chart polygons with ly_rect (one call to ly_rect for each classification) and use custom legend entries for those and then add a custom legend entry for ly_abline.
I do not know the answer to #3.

spplot/lattice: objects not drawn/overdrawn

I have a grid and I want to produce a map out of this grid with some map elements (scale, north arrow, etc). I have no problem drawing the grid and the coloring I need, but the additional map elements won't show on the map. I tried putting first=TRUE to the sp.layout argument according to the sp manual, but still no success.
I reproduced the issue with the integrated meuse dataset, so you may just copy&paste that code. I use those package versions: lattice_0.20-33 and sp_1.2-0
library(sp)
library(lattice) # required for trellis.par.set():
trellis.par.set(sp.theme()) # sets color ramp to bpy.colors()
alphaChannelSupported = function() {
!is.na(match(names(dev.cur()), c("pdf")))
}
data(meuse)
coordinates(meuse)=~x+y
data(meuse.riv)
library(gstat, pos = match(paste("package", "sp", sep=":"), search()) + 1)
data(meuse.grid)
coordinates(meuse.grid) = ~x+y
gridded(meuse.grid) = TRUE
v.uk = variogram(log(zinc)~sqrt(dist), meuse)
uk.model = fit.variogram(v.uk, vgm(1, "Exp", 300, 1))
meuse[["ff"]] = factor(meuse[["ffreq"]])
meuse.grid[["ff"]] = factor(meuse.grid[["ffreq"]])
zn.uk = krige(log(zinc)~sqrt(dist), meuse, meuse.grid, model = uk.model)
zn.uk[["se"]] = sqrt(zn.uk[["var1.var"]])
meuse.sr = SpatialPolygons(list(Polygons(list(Polygon(meuse.riv)),"meuse.riv")))
rv = list("sp.polygons", meuse.sr, fill = "lightblue")
sampling = list("sp.points", meuse.riv, color = "black")
scale = list("SpatialPolygonsRescale", layout.scale.bar(),
offset = c(180500,329800), scale = 500, fill=c("transparent","black"), which = 4)
text1 = list("sp.text", c(180500,329900), "0", cex = .5, which = 4)
text2 = list("sp.text", c(181000,329900), "500 m", cex = .5, which = 4)
arrow = list("SpatialPolygonsRescale", layout.north.arrow(),
offset = c(181300,329800),
scale = 400, which = 4)
library(RColorBrewer)
library(lattice)
trellis.par.set(sp.theme())
precip.pal <- colorRampPalette(brewer.pal(7, name="Blues"))
spplot(zn.uk, "var1.pred",
sp.layout = list(rv, sampling, scale, text1, text2),
main = "log(zinc); universal kriging standard errors",
col.regions=precip.pal,
contour=TRUE,
col='black',
pretty=TRUE,
scales=list(draw = TRUE),
labels=TRUE)
And that's how it looks...all naked:
So my questions:
Where is the scale bar, north arrow, etc hiding? Did I miss something? Every example I could find on the internet looks similar to that. On my own dataset I can see the scale bar and north arrow being drawn at first, but as soon as the grid is rendered, it superimposes the additional map elements (except for the scale text, that is shown on the map - not the bar and north arrow for some reason I don't seem to comprehend).
The error message appearing on the map just shows when I try to add the sampling locations sampling = list("sp.points", meuse.riv, color = "black"). Without this entry, the map shows without error, but also without additional map elements. How can I show the sampling points on the map (e.g. in circles whose size depends on the absolute value of this sampling point)?
This bothered me for many, many hours by now and I can't find any solution to this. In Bivand et al's textbook (2013) "Applied Spatial Data Analysis with R" I could read the following entry:
The order of items in the sp.layout argument matters; in principle objects
are drawn in the order they appear. By default, when the object of spplot has
points or lines, sp.layout items are drawn before the points to allow grids
and polygons drawn as a background. For grids and polygons, sp.layout
items are drawn afterwards (so the item will not be overdrawn by the grid
and/or polygon). For grids, adding a list element first = TRUE ensures that
the item is drawn before the grid is drawn (e.g. when filled polygons are added). Transparency may help when combining layers; it is available for the
PDF device and several other devices.
Function sp.theme returns a lattice theme that can be useful for plots
made by spplot; use trellis.par.set(sp.theme()) after a device is opened
or changed to make this effective.
However, also with this additional information I wasn't able to solve this problem. Glad for any hint!
The elements you miss are being drawn in panel four, which does not exist, so are not being drawn. Try removing the which = 4.
meuse.riv in your example is a matrix, which causes the error message, but should be a SpatialPoints object, so create sampling by:
sampling = list("sp.points", SpatialPoints(meuse.riv), color = "black")
When working from examples, my advice is to choose examples as close as possible to what you need, and only change one thing at a time.

Resources