Skip to content

Converting Stacked and Grouped Bar Plot in Matplotlib to Dash. #3251

Closed
@tanya-pix

Description

@tanya-pix

Hi
I have the following code for converting a Matplotlib plot into Plotly. However, this gives me an error 'XAxis' object has no attribute '_gridOnMajor' despite having changed it to axis._major_tick_kw['gridOn'].
How should I convert this graph into a Dash graph( so that I can put it on a webpage)?
Additionally, is there any way to make it interactive(like other Plotly plots)?

import pandas as pd
import matplotlib.pyplot as plt
import numpy as np
from matplotlib.ticker import MaxNLocator
import matplotlib.gridspec as gridspec
import seaborn as sns
import plotly 
plt.style.use('ggplot')
colors = ['#FF0000','#FFA500','#90EE90','#006400','#FF00FF','#4169e1','#add8e6','#FFD700','#696969']
sns.set_palette(sns.color_palette(colors))

SDG=(r'C:\Users\Admin\Desktop\Final Templates for Code\SDG Coverage.xlsx')
df = pd.read_excel(SDG,header=0,names=["Cluster", "Bar", "Bar_part", "Count"])
df = df.groupby(["Cluster", "Bar", "Bar_part"])["Count"].sum().unstack(fill_value=0)

def get_grid_style(axis):
    gridlines = axis.get_gridlines()
    if axis._major_tick_kw['gridOn'] and len(gridlines) > 0:
        color = export_color(gridlines[0].get_color())
        alpha = gridlines[0].get_alpha()
    
clusters = df.index.levels[0]
inter_graph = 0
maxi = np.max(np.sum(df, axis=1))
total_width = len(df)+inter_graph*(len(clusters)-1)
fig = plt.figure(figsize=(total_width,10))
gridspec.GridSpec(1, total_width)
axes=[]

ax_position = 0
for cluster in clusters:
    subset = df.loc[cluster]
    ax = subset.plot(kind="bar", stacked=True, width=0.5, ax=plt.subplot2grid((1,total_width), (0,ax_position), colspan=len(subset.index)))
    axes.append(ax)
    ax.set_title(cluster)
    ax.set_xlabel("")
    plt.xticks(rotation= 41,ha='right')
    plt.subplots_adjust(bottom=0.15)
    ax.set_ylim(0,maxi+1)
    ax.yaxis.set_major_locator(MaxNLocator(integer=True))
    ax_position += len(subset.index)+inter_graph

for i in range(1,len(clusters)):
    axes[i].set_yticklabels("")
    axes[i-1].legend().set_visible(False)
axes[4].set_xlabel("Sustainable Development Goals",fontsize="x-large")

fig.suptitle('SDG Coverage', fontsize="x-large")
legend = axes[-1].legend(loc='upper left', fontsize=16, framealpha=1).get_frame()
legend.set_linewidth(3)
legend.set_edgecolor("black")

import plotly.tools as tls
plotly_fig = tls.mpl_to_plotly(fig)
plotly_fig

Metadata

Metadata

Assignees

No one assigned

    Labels

    No labels
    No labels

    Type

    No type

    Projects

    No projects

    Milestone

    No milestone

    Relationships

    None yet

    Development

    No branches or pull requests

    Issue actions