How do I define color groups based on numerical threshold values for ggplot2 barplot - colors

I want to make a bar plot in ggplors where the value below zero is in red color. However, I got this graph instead of red color below zero value. Can anyone help me to solve the problem above? I have tried following some manual code but could not find the answers still.
Greatly appreciate for your help.
I tried this code:
Central_Java %>%
mutate(Category = factor(Category, levels = c("Minimum", "Medium", "Slightly Ideal", "Ideal"))) %>%
ggplot(aes(Province, Above_Below_Required_Staff, fill = Available_Staff, color=ifelse(Above_Below_Required_Staff>0, "red", "blue"))) +
xlab ("MPAs in Central Java\n(n=1)") + ylab ("Percent of Required Staff")+
ylim(-100,100)+
facet_wrap(~Category, ncol = 4)+
geom_bar(stat="identity")+
geom_hline(yintercept = 0, colour = "black") +
theme_light(base_size = 20) +
theme_bw()+
theme(text=element_text(size=19))+
ggtitle("Level of MPA Staff Capacity")+ theme(plot.title = element_text(hjust = 0.5))+
theme(
panel.grid.major = element_blank(),
panel.grid.minor = element_blank()
)
'''
Best,
[enter image description here] (https://i.stack.imgur.com/HPvZe.png)

Related

How to map discrete colours in a Plotly Sunburst chart in r

I am very new to using plotly in rstudio and have come up against a problem with mapping discrete colours (stored as hex codes in the field color) to each of the slices in my ids field.
I have included my code below:
df %>%
plot_ly(
color = I("black"),
marker = list(colors = ~color)) %>%
add_trace(ids = df$ids,
labels = df$labels,
parents = df$parents,
type = 'sunburst',
maxdepth = -1,
domain = list(column = 0)) %>%
layout(sunburstcolorway = df$color)
This is the resulting sunburst diagram I get using this code, which is obviously not ideal:
Ideally the first four levels would have the same colour, and then different hex colour codes are used for slices that are labelled "Poor","Moderate","GwC" or "Good".
A csv file of my data frame used above is available here.
I finally managed to nut out how to map my colour field to the background colours on the sunburst chart - have updated the code in original post. All that was required was to insert the following code segment:
plot_ly(
marker = list(colors = ~color))
Below is the output chart:

Create a table using Vpython

Use of the VPython library to create a small table in a simulated 3D space
this is what I've got
top = box(pos=vector(-1,4,4),
axis=vector(-1.5,0,-1.5),
size=vector(18,0.29,10),
up=vector(5,25,5),
color = color.blue)
leg1 = cylinder(pos=(-3,-3,0),
axis=vector(0,7,0), radius=0.45,
color = color.green )
leg2 = cylinder(pos=vector(3.5,-5,3),
axis=vector(0,9,0), radius=0.45,
color = color.green )
leg3 = cylinder(pos=vector(10.5,-3.9,2),
axis=vector(0,9,0), radius=0.45,
color = color.green )
leg4 = cylinder(pos=vector(-11.5,-6.5,-2.2),
axis=vector(0,11,0), radius=0.45,
color = color.green )
The first image is what I got and the second image is what I want, but turned upside down as a table would
Try drawing out the table top and legs on paper
The up of the table top should be default
The legs should have the same "length"
To have the legs point downwards use a negative y
If the center of your table is 0,0,0 then the legs will reflect each other's positions in reference to that.

Change color and legend of plotLearnerPrediction ggplot2 object

I've been producing a number of nice plots with the plotLearnerPrediction function in the mlr package for R. They look like this. From looking into the source code of the plotLearnerPrediction function it looks like the color surfaces are made with geom_tile.
A plot can for example be made by:
library(mlr)
data(iris)
#make a learner
lrn <- "classif.qda"
#make a task
my.task <- makeClassifTask(data = iris, target = "Species")
#make plot
plotLearnerPrediction(learner = lrn, task = my.task)
Now I wish to change the colors, using another red, blue and green tone to match those of some other plots that I've made for a project. for this I tried scale_fill_continuous and scale_fill_manual without any luck (Error: Discrete value supplied to continuous scale) I also wish to change the legend title and the labels for each legend entry (Which I tried giving appropriate parameters to the above scale_fill's). There's a lot of info out there on how to set the geom_tile colours when producing the plot, but I haven't found any info on how to do this post-production (i.e. in somebody else's plot object). Any help would be much appreciated.
When you look into the source code you see how the plot is generated and then you can see which scale has to be overwritten or set.
In this example it's fairly easy:
g = plotLearnerPrediction(learner = lrn, task = my.task)
library(ggplot2)
g + scale_fill_manual(values = c(setosa = "yellow", versicolor = "blue", virginica = "red"))

Bokeh: Control colors on Donut chart

I am using Bokeh to create a series of pie charts with bokeh.charts.Donut. The charts are based off of subsets of the same DataFrame, and all have the same category labels. I want to ensure that the same categories are displayed in the same colors across the various charts, but I haven't been able to figure out a consistent way of controlling the colors.
Currently I am sorting my input DataFrames by the label, and passing the same array of colors to the palette property of Donut. This still does not work as intended. Code is as follows:
main_colors = ['#10A400','#DB5E11','#C8C500','#CF102E','#00AFA8','#82BC00','#A40D7A','#FF7100','#1349BB']
#split out youth health problems
for_youth_health = detailed_assessment_safety.loc[detailed_assessment_safety.youth_health_prob.notnull()]
youth_health_issues = pd.DataFrame(for_youth_health.youth_health_prob.str.split(' ').tolist())
for col in youth_health_issues.columns:
newcol = 'youth_health_prob_' + str(col)
youth_health_issues = youth_health_issues.rename(columns={col:newcol})
youth_health_trans = pd.melt(youth_health_issues)
youth_health_trans = youth_health_trans.loc[youth_health_trans.value.notnull()]
youth_health_trans['issue_text'] = youth_health_trans.value.map(map_health_issues)
youth_health_trans.drop('value',axis=1,inplace=True)
youth_health_trans.sort_values(by='issue_text',ascending=True,inplace=True)
#pie of youth health issues
youth_health_issues = Donut(youth_health_trans,label='issue_text',
values='variable',agg='count',plot_width=plot_width,
plot_height=plot_height,title='Reported Youth Health Issues',
color=main_colors)
hover = HoverTool(point_policy='follow_mouse')
hover.tooltips = [('Number Reported','#values'),('Health Issue','#issue_text')]
youth_health_issues.add_tools(hover)
#split out adult health problems
for_adult_health = detailed_assessment_safety.loc[detailed_assessment_safety.adult_health_prob.notnull()]
adult_health_issues = pd.DataFrame(for_adult_health.adult_health_prob.str.split(' ').tolist())
for col in adult_health_issues.columns:
newcol = 'adult_health_prob_' + str(col)
adult_health_issues = adult_health_issues.rename(columns={col:newcol})
adult_health_trans = pd.melt(adult_health_issues)
adult_health_trans = adult_health_trans.loc[adult_health_trans.value.notnull()]
adult_health_trans['issue_text'] = adult_health_trans.value.map(map_health_issues)
adult_health_trans.drop('value',axis=1,inplace=True)
adult_health_trans.sort_values(by='issue_text',ascending=True,inplace=True)
#pie of adult health issues
adult_health_issues = Donut(adult_health_trans,label='issue_text',
values='variable',agg='count',plot_width=plot_width,
plot_height=plot_height,title='Reported Adult Health Issues',
palette=main_colors)
hover = HoverTool(point_policy='follow_mouse')
hover.tooltips = [('Number Reported','#values'),('Health Issue','#issue_text')]
adult_health_issues.add_tools(hover)
What's the proper way to map the same categories of Donut charts to colors across multiple charts? The other idea that I had was inserting a column into the DataFrame that mapped label values to colors, and then passing that column as an argument to Donut, but I couldn't make that work either. Any help is much appreciated.
After some experimentation, it turns out that when you pass an array of colors to the palette argument of Donut, the colors are associated with the donut slices based on an alphabetical sort of the slice name. So, the first color in your array of palette colors will be associated with the slice with the alphabetically first name, etc.

Appropriate Syntax For Alternating Row Colors

I am using this code:
=IIF(RunningValue(Fields!cost_center_id.Value, CountDistinct, nothing) Mod 2, "White", "Gainsboro")
But its result is not good. I think it's because of Fields!cost_center_id.Value. Can anybody tell me the most appropriate code?
And why the footer (Total) has also shade thought I haven't put code in it? Help me.
Thanks in advance.
Screenshots:
I used this code for the 3rd picture.
= IIF(RowNumber("LCSRDBDataSet_CostCenterSummary") Mod 2 = 0, "White", "Gainsboro")
The reason your expression doesn't work is because your id values might have gaps or not be ordered correctly.
One of these following expressions should give the wanted behavior.
= IIF(RowNumber(Nothing) Mod 2 = 0, "White", "Gainsboro")
= IIF(RowNumber("YourDataSet") Mod 2 = 0, "White", "Gainsboro")
You need to define the expression for the BackgroundColorproperty of the data row. The footer row (total) should be below the data row, and thus have no expression for it's background color, unless you want it to be different to the final row.

Resources