customising individual bars in group barmode - colors

Is there a way to customize the colors of individual bars in a group bar chart?
In here, under the section "Customizing Individual Bar Colors" shows the manner in which customization can be done for the regular bar charts.
But in barmode=group settings, I could only set the colors for the group. Am wondering how I can customize the colors for a single bar.
fig_company = px.bar(
df,
y = "company",
x = "revenue",
color = "region",
orientation = 'h',
text_auto = True,
barmode="group",
color_discrete_map={
"south":"#DBCFB0",
"north":"#545775"}
)

Related

How to have a legend for colored edges in Julia plots?

Here is a minimal working code from Julia Discourse:
using LightGraphs
using GraphPlot
using Colors
g = graphfamous("karate")
membership = [1,1,1,1,1,1,1,1,2,1,1,1,1,1,2,2,1,1,2,1,2,1,2,1,1,1,1,2,1,1,2,1,1,1]
nodecolor = [colorant"lightgrey", colorant"orange"]
nodefillc = nodecolor[membership]
colors = [colorant"lightgray" for i in 1:78]
colors[42] = colorant"orange"
gplot(g, nodefillc=nodefillc, layout=circular_layout, edgestrokec=colors, edgelabel=1:78)
Which produces
I would like to add a legend on top left (or top right) so that I can easily tell what are the meaning of the two types of edges. Additionally, if there is also a way to legend what are the two types of nodes that would be a great plus!
For instance, grey edges would be named: "regular edges" and green edges would be "backup edges". Similarly, grey nodes would be "regular nodes" and orange nodes would be "backup nodes"!
I could not find a keyword in gplot for what I am searching!

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:

Plotly - clicking on legend items - how to make an initial setting?

When someone clicks on a legend item, it becomes grey, and the data disappears, for instance, here. It is possible to set that an item from a legend will be grey after opening the .HTML output and will appear after clicking of that? Thank you
You can do that using the visible property on the trace, just set visible='legendonly'.
visible
Type: enumerated , one of ( True | False | "legendonly" )
Default: True
Determines whether or not this trace is visible. If "legendonly", the
trace is not drawn, but can appear as a legend item (provided that the
legend itself is visible).
A common use case is when one has a lot of traces and wants to show only a few of them initially, eg. with plotly.express :
import plotly.express as px
df = px.data.gapminder().query("continent == 'Europe'")
# Nb. This creates one trace per country (color='country'), with each trace `name`
# inheriting the value of its respective country.
fig = px.line(df, x='year', y='gdpPercap', color='country', symbol="country")
# Arbitrary selection
sel = ['Norway', 'Ireland', 'France', 'Switzerland']
# Disable the traces that are not in the selection
fig.update_traces(selector=lambda t: t.name not in sel, visible='legendonly')
fig.show()

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.

Fix Bar Chart Width and Spacing between bars in JFreeChart

I have stacked bar chart in which the number of columns is dynamic, can change from 1 to n columns. I want the spacing between the charts and width of the bar to be consistent. How do I fix it. Please suggest solutions / ideas.
In a Stacked Bar chart, you can change the spacing between bars using
CategoryAxis.setLowerMargin
CategoryAxis.setMargin and
CategoryAxis.setUpperMargin
Code is below
protected JFreeChart generateGraph() {
CategoryAxis categoryAxis = new CategoryAxis("Categories");
categoryAxis.setLowerMargin(.01);
categoryAxis.setCategoryMargin(.01);
categoryAxis.setUpperMargin(.01);
categoryAxis.setCategoryLabelPositions(CategoryLabelPositions.UP_90);
ValueAxis valueAxis = new NumberAxis("Values");
StackedBarRenderer renderer = new StackedBarRenderer();
renderer.setBarPainter(new StandardBarPainter());
renderer.setDrawBarOutline(false);
renderer.setShadowVisible(false);
renderer.setBaseItemLabelsVisible(true);
renderer.setBaseItemLabelGenerator(new StandardCategoryItemLabelGenerator());
CategoryPlot plot = new CategoryPlot( _dataset,
categoryAxis,
valueAxis,
renderer);
plot.setOrientation(PlotOrientation.VERTICAL);
JFreeChart chart = new JFreeChart( "Title",
JFreeChart.DEFAULT_TITLE_FONT,
plot,
true);
//ChartFactory.getChartTheme().apply(_chart);
return chart;
}
StackedBarRenderer devotes some effort to making the "spacing between the [bars] and width of the bar to be consistent." It's not clear what you want it to do differently as the number of columns changes. The relevant geometry is determined by the parent BarRenderer in such methods as calculateBarWidth(), which can be overridden as desired. Also, verify that there is a value for each category in each series.

Resources