3
votes

I am trying to change the colors of a stack bar chart that I draw in python with plotly and cufflinks (cufflinks library allows to draw chart directly form a dataframe which is super useful).

Let's take the following figure (I use jupyter notebook):

import plotly.plotly as py
import cufflinks as cf

cf.set_config_file(offline=True, world_readable=True, theme='white')

df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
df.iplot(kind='bar', barmode='stack')

How do you implement a new color palette using the above code? I would like to use the 'Viridis' color palette. I haven't found a way to modify the colors of the graph or to use a color palette to automatically color differently the different stack of the bar chart. Does one of you knows how to do it?

Many thanks for your help,

3

3 Answers

5
votes
trace0 = go.Scatter(
    x = foo,
    y = bar,
    name = 'baz',
    line = dict(
        color = ('rgb(6, 12, 24)'),
        width = 4)
)

This allows you to change the color of the line or you could use

colors = `['rgb(67,67,67)', 'rgb(115,115,115)', 'rgb(49,130,189)', 'rgb(189,189,189)']`

for separate lines of a graph. To use the specified color gradient try

data = [
    go.Scatter(
        y=[1, 1, 1, 1, 1],
        marker=dict(
            size=12,
            cmax=4,
            cmin=0,
            color=[0, 1, 2, 3, 4],
            colorbar=dict(
                title='Colorbar'
            ),
            colorscale='Viridis'
        ),
        mode='markers')
]
1
votes

Found an answer to my problem:

import plotly.plotly as py
import cufflinks as cf
from bokeh.palettes import viridis

cf.set_config_file(offline=True, world_readable=True, theme='white')
colors = viridis(4)
df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
fig = df.iplot(kind='bar', barmode='stack',asFigure = True)

for i,color in enumerate(colors):
    fig['data'][i]['marker'].update({'color': color})
    fig['data'][i]['marker']['line'].update({'color': color})

py.offline.iplot(fig)
1
votes

To build upon the answer of @Peslier53: You can specify colors or a colorscale directly within df.iplot():

import plotly.plotly as py
import cufflinks as cf
from bokeh.palettes import viridis

cf.set_config_file(offline=True, world_readable=True, theme='white')
colors = viridis(4)
df = pd.DataFrame(np.random.rand(10, 4), columns=['A', 'B', 'C', 'D'])
df.iplot(kind='bar', barmode='stack', colors = colors)

This saves you some lines of code and makes plotting very convenient. It also works with any list of colors (depending on the graph type, heat maps need a color gradient instead of a color list for example), so you can also use custom colors.