rgb() with ggplot2 in R - r

In ggplot2, we have the option of setting colours by name or hex code. Is there any way to use rgb values in the same way? I searched the docs but the quick answer seems to be 'no'. (The reason I would like to use rgb is that I have some colours that I am going to use for some plots, and I have them all in rgb format. I can get the hex from places like here, but it would be great if I could just enter the values straight into ggplot().

You can use the function rgb(r, g, b) to convert fractional RGB values to hex:
rgb(0.1,0.2,0.3)
[1] "#1A334D"
If your values are based on 8-bit color (or any other limit), you can use the maxColorValue option to specify the maximum number:
rgb(207, 31, 46, maxColorValue = 255)
[1] "#CF1F2E"

Related

gnuplot vector arrow length and streamlines

I have already asked about vector fields in here. Now I want to know a bit more about it.
How can I make it so that each arrow has the same fixed length and define the magnitude of the value by color?
And is it still not possible to plot streamlines in gnuplot? If possible, how can I do that?
For now I have this and need to upgrade it.
set term pngcairo
set title 'Navier-Stokes Equation'
set terminal png size 1280,720
set output 'vec.png'
plot 'vec' u 1:2:($3/$5):($4/$5) w vec t 'Vector Field'
UPDATE
Thanks to #theozh I've got what I wanted. I want to share my result as it could be useful for someone else.
Now I use these instructions to plot my vector field.
reset session
set size square
set palette rgb 33, 15, 10
set term pngcairo
set title 'Navier-Stokes Equation'
set terminal png size 1280, 720
set output 'vec.png'
plot 'vec.dat' u 1:2:(0.08*$3):(0.08*$4):(sqrt($3**2+$4**2)) w vec lw 2 lc palette notitle
About the same length: simply normalize your vectors.
About the color:
you can add a "column" and the end. The last column will define the color according to a palette.
I don't know about streamlines (what exactly they are and how to possibly realize them).
With the example script:
Script: (Edit: define function for length L() to make plot command shorter and clearer.)
### plot with normalized/scaled vectors
reset session
set size square
set samples 25
set palette rgb 33,13,10
set key noautotitle
Scale = 0.5
L(colX,colY) = sqrt(column(colX)**2+column(colY)**2)
plot [-5:5] '++' u 1:2:(Scale*$1/L(1,2)):(Scale*$2/L(1,2)):(L(1,2)) w vec lc palette
### end of script

Line plot with color gradient

Is there a way to create a plot in IDL with a color gradient to it? What I'm looking for is similar to this Matlab question. The best I know how to do is to plot each segment of the line in a for loop, but this seems rather cumbersome:
x = float(indgen(11) - 5)
y = x ^ 2
loadct, 2, /silent
!p.background = 255
plot, x, y
for i = 0, 9 do begin
oplot, x(i:i+1), y(i:i+1), color = i * 20, thick = 4
endfor
I'm using IDL 8.2 if that makes a difference.
I had the same issue once and there seems to be no (simple) solution. Though I surrendered, you can try using a RGB-vector and the VERT_COLORS-keywords, provided by the PLOT function:
A vector of indices into the color table for the color of each vertex
(plot data point). Alternately, a 3xN byte array containing vertex
color values. If the values supplied are not of type byte, they are
scaled to the byte range using BYTSCL. If indices are supplied but no
colors are provided with the RGB_TABLE property, a default grayscale
ramp is used. If a 3xN array of colors is provided, the colors are
used directly and the color values provided with RGB_TABLE are
ignored. If the number of indices or colors specified is less than the
number of vertices, the colors are repeated cyclically.
That would change the appearence more discrete, but maybe it will help you.
I have a routine MG_PLOTS which can do this in direct graphics:
IDL> plot, x, y, /nodata, color=0, background=255
IDL> mg_plots, x, y, color=indgen(10) * 20, thick=4
Of course, it is just a wrapper for what you where doing manually.

Map values to viridis colours in r

How do I create a colour scale function in r with a pre-defined scale (like viridis from library("viridis")?
The question is not how to use it within ggplot, but how to build a function I can feed arbitrary values within the specified value domain to and retrieve the according colour strings (rgb, hex or any other output format) from.
colorRamp and colorRampPalette seem to interpolate only between 2 colours within a given colour space. But how would I go about this with viridis for example?
EDIT:
Thanks to #sconfluentus' answer I wrote the following function that does what I want (w/o safety checks):
library("viridis")
number_vector <- c(0.772, 1.235, 5.78, 8.890, 10.543, 14.702)
map_viridis <- function(vec, num) {
vector_expanded <-round(vec, 1) * 10 # expand to allow for decimal precision
vector_exp_range <- max(vector_expanded) - min(vector_expanded)
colour_vector <- viridis(vector_exp_range + 1) # get vector of colour values for all possible decimals between min and max value
value_to_colour <- colour_vector[num * 10 - min(vector_expanded) + 1] # retrieve colour value for number
return(value_to_colour)
}
map_viridis(number_vector, 0.8) # returns "#440154FF"
map_viridis(number_vector, 3.4) # returns "#424086FF"
map_viridis(number_vector, 14.7) # returns "#FDE725FF"
Just wondering if there's not a more direct way to achieve this result?
Viridis itself is capable creating the values you are looking for provided you use it correctly in your own function and you know how many arbitrary values will be created.
viridis(12)
[1] "#440154FF" "#482173FF" "#433E85FF" "#38598CFF" "#2D708EFF" "#25858EFF" "#1E9B8AFF"
[8] "#2BB07FFF" "#51C56AFF" "#85D54AFF" "#C2DF23FF" "#FDE725FF"
So you could create a function which takes your domain, calculates the length of values in it and then creates a series of colors for each manipulating your data any way you choose. The basis for it would be like this
num_vals=length(x) # substitute nrow for length if you have rows instead of a list
col_pal = viridis(num_vals)
As long as the set is ordered then you can simply use data[1] and col_pal[1] to associate them in pairs..or you could create a list of pairs and colors depending on how you choose to substitute them into your function.
or you could create a ramp with colorRampPalette as such
map_colors<-colorRampPalette(viridis(12)) # this would create 12 viridis colors
You can use library(colourvalues) (on CRAN 1st October 2018) to assign colours to values. The default palette is viridis.
number_vector <- c(0.772, 1.235, 5.78, 8.890, 10.543, 14.702)
colourvalues::colour_values(number_vector)
# [1] "#440154FF" "#470E60FF" "#2E6E8EFF" "#20A486FF" "#44BF70FF" "#FDE725FF"
I think this does what you want. Most of this was copied from the source of the viridis function. It takes in values between 0 and 1 and returns a color a corresponding fraction of the way along the viridis map.
get_viridis_color <- function(x, opt="D", begin=0, end=1, reverse=FALSE) {
x <- x * (end - begin) + begin
cmap <- viridisLite::viridis.map[viridisLite::viridis.map$opt == opt,]
if (reverse) cmap <- cmap[rev(seq_len(nrow(cmap))),]
map_rgbs <- grDevices::rgb(cmap$R, cmap$G, cmap$B)
ramp <- grDevices::colorRamp(map_rgbs, space="Lab", interpolate="spline")
out_rgbs <- ramp(x) / 255
grDevices::rgb(out_rgbs[,1], out_rgbs[,2], out_rgbs[,3])
}
Values outside [0, 1] are not handled; for some reason this means negative numbers are #00FF00 and numbers greater than 1 are black. begin and end work like they do in viridis(), but reversing direction of the colormap is a boolean reverse argument instead of the 1 or -1 direction argument. Different values of opt give magma ("A"), inferno ("B"), and plasma ("C") maps instead of viridis.

Colour-coded 3D Plot in R

I am new to R, so can someone please help with this?
I have a data frame with 4 columns: x,y,z and freq. One row in this frame represents one point in 3D space (x,y,z are x-,y- and z- coordinates respectively) and it's frequency. I want to plot these points and make these points coloured such that the color is decided by the frequency. For eg: All points with frequency 0 are blue, between 1 and 5 are red, between 5 and 10 are orange, between 10 and 15 are yellow and so on. Some points can have a frequency of 0 also. But I don't know the range of frequency. Max no of colors to be used is 10. Also, there should be a scale explaining the meaning of colors.
I have been trying to correct the following code and make it work, but it`s just not working:
lev <- levels(factor(t$freq));
n <- as.numeric(lev);
n <- n+1;
plot3d(t$x,t$z,t$z,col=n);
Please help! Thank you.
PS- Please tell the solution using rgl package
PPS - I have been trying to manipulate the col arguement in plot3d function of rgl package, but I am unable to get the desired result.
I would load package rgl and do
plot3d(x,y,z, col=colors)
That means that you should prepare a list of color values that is of the same length as x,y,z lists so that you have a color selected for each x,y,z point.
the other part would be to make the list. I would try
givecolor = function(freq){
if(freq < 1) "red"
else if ....
}
colors = sapply(mydataframe[,"freq"], givecolor)
You just need to build a vector of colors that is the same length as the number of points you are plotting. You then pass this vector as the col argument to the rgl plot3d() function. See this page for a demonstration that uses the iris dataset: http://planspace.org/2013/02/03/pca-3d-visualization-and-clustering-in-r/
First you should select a palette you like and pick the number of colors you want, e.g. palette=rainbow(10). Then use a factor you get from splitting your data 10 ways to set your color from the palette.
See 3d scatterplot in R using rgl plot3d - different size for each data point? for how to effectively split a dataframe by a newly created factor. That question is w.r.t. size, but it also works for color.

Obtaining Left and Right Arrows As Plot Symbols in R

I have a data set that I would like to plot in R that contains a factor with categories of "left" and "right". I'd like to use plot symbols that somehow indicate direction, with a simple solution being triangles that point left and right. However, the standard symbol list in R only includes triangles that point up and down (pch = 2,6 or 24,25 for example, with a complete symbol list here). What's the most straightforward method of plotting triangles that point left and right?
Note: I've tried using < and > from the ascii set (pch = 60 and 62), although I'd like symbols that have better visibility because I'll eventually be using these figures on a projector. I'll fall back on these symbols if there isn't a better solution.
plot(x=0, type="n")
text(1, .5, paste0("0.5", intToUtf8(9660)))
text(1, -.5, paste0("-0.5", intToUtf8(9650)))
Left: 9664, right: 9654

Resources