Bokeh: Control colors on Donut chart - python-3.x

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.

Related

Plotly does not color-code my chart according to the variable indicated

I have the problem that when I concatenate two csv and create a column "Version" with string values, plotly does NOT generate the classification of each of the values, in this case 1 and 2. However, when this variable is numeric, it does generate a continuous classification (I need a discrete classification).
Image shows concatenation and data type
Two legends are observed, but only one color is observed
This is an example of how it doesn't work. However, if I change the variable to continuous, it does work.
I am generating this block to generate graphs for each type of group. Which should be my final result.
grouped = df_final.groupby('Name')
plots = []
for name, group in grouped:
# create a new figure for the group
fig = px.scatter(group.reset_index(), x="Time", y="Observed", opacity=1, width=800, height=600,
color = "Version)
fig.show()
This block generates the chart with its legend, but does not show the colors in the chart.
I am starting with python and plotly, any help would be appreciated.
I'm trying to understand why plotly doesn't sort my string variables

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:

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"))

Formatted String from List Psychopy

My task is a variation of a multiple object tracking task. There are 7 circles on the screen. It randomly selects 3 circles to change the color (red, green, blue) briefly to indicate to the participant to track these circles. After the color change, all the circles will change to the same color and the circles will move for a period of time. When the circles stop moving, a response prompt will appear, where the participant is to select one of the three colored circles ('select the red/green/blue circle'). I am having difficulty inserting which color circle to select into the formatted string. I keep getting the error message: unsupported operand type(s) for %: 'TextStim' and 'list'
I'm not sure if I need to or how to convert these lists, so any help would be much appreciated!
n_targets = 7 #seven locations
circles = [] #setting up the circle stimuli
for i in range(n_targets):
tmp = visual.Circle(win,radius = 27,units = 'pix',edges = 32,fillColor='white',lineColor = 'black',lineWidth = 1, pos=(posx[i],posy[i]))
circles.append(tmp)
cols = ['blue','red','green'] #3 colors the circles will change to
targets = random.sample(circles,3) #randomly select 3 of the 7 circles
TrialTarget = random.sample(targets, 1) #select 1 of the 3 circles to be the target for the trial
#code for movement would go here (skipping since it is not relevant)
#at end of trial, response prompt appears and ask user to select target and is where error occurs
ResponsePrompt = visual.TextStim(win, text = "Select the %s circle") %TrialTarget
In this line, you are trying to create a formatted string from a TextStim object and a Circle stimulus object rather than a string object and another string object:
ResponsePrompt = visual.TextStim(win, text = "Select the %s circle") %TrialTarget
i.e. ResponsePrompt is clearly a visual.TextStim, as you are creating it as one, and I think TrialTarget is a visual.Circle stimulus, as you randomly sample it from a list of Circles.
I'm guessing that you actually want to incorporate the colour label into the prompt text. So to fix both problems (the type incompatibility and the formatting syntax), you need to actually get one of the elements of cols, called say trialColour, and use something like this:
ResponsePrompt = visual.TextStim(win, text = "Select the %s circle" % trialColour)
i.e. here trialColour is actually a string, and the formatting operation is brought inside the brackets so it applies directly to the text string "Select the %s circle"
That should hopefully fix your immediate problem. You might also want to investigate using random.shuffle() to shuffle lists in place instead of random.sample().

two textplots in one plot

I have been trying to work with textplot in R and am unsure if my question is possible or not, I know that par() can't be used to place two textplots in one plot. I have been using a page and this code to try and figure things out.
My question is: Is it possible to have two textplots within the same plot?
For example, in the par(mfrow=c(1,1)) scenario below, plot 1 is a texplot of species length. Say I wanted to replicate that textplot twice in that plot. Is that possible?
based on this site:
http://svitsrv25.epfl.ch/R-doc/library/gplots/html/textplot.html
textplot(version)
data(iris)
par(mfrow=c(1,1))
info <- sapply( split(iris$Sepal.Length, iris$Species),
function(x) round(c(Mean=mean(x), SD=sd(x), N=gdata::nobs(x)),2) )
textplot( info, valign="top" )
title("Sepal Length by Species")
What I want to do is put a second textplot within that plot, underneath the original. For arguments sake, replicating that textplot twice in the plot.
Is this possible?
Thanks!
Maybe you've figured it out in the last four months but I thought I'd chip in an answer anyway.
The code provided is most of the way towards doing what you require already, you just have to provide some additional inputs to title() and/or par(). Namely specify that the title is to be above both of the plots by using title("your title", outer = TRUE) and you can further adjust the position of the title with an option in par(), use par(mfrow = c(2,1), oma = c(0,0,"top",0)). Hopefully this answers your question.
require('gplots')
data(iris)
info <- sapply(split(iris$Sepal.Length, iris$Species),
function(x) round(c(Mean = mean(x), SD = sd(x), N = gdata::nobs(x)),2))
## Replace top with a numerical value to control the position of the title with respect to the
## top of the page.
par(mfrow = c(2,1), oma = c(0,0, top ,0))
textplot(info, valign = "top")
textplot(info, valign = "top")
title("Sepal Length by Species", outer = TRUE)

Resources