plotly / plotly.py

The interactive graphing library for Python :sparkles: This project now includes Plotly Express!
https://plotly.com/python/
MIT License
16.02k stars 2.54k forks source link

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

Closed tanya-pix closed 2 months ago

tanya-pix commented 3 years ago

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
nicolaskruchten commented 3 years ago

Unfortunately we don't have a good solution to grouped-and-stacked bars right now.

tanya-pix commented 3 years ago

Unfortunately we don't have a good solution to grouped-and-stacked bars right now. Thankyou for your reply. How could I generate a static image and then have that on my webpage(which is to be created using dash)?

gvwilson commented 2 months ago

Hi - we are trying to tidy up the stale issues and PRs in Plotly's public repositories so that we can focus on things that are still important to our community. Since this one has been sitting for several years, I'm going to close it; if it is still a concern, please add a comment letting us know what recent version of our software you've checked it with so that I can reopen it and add it to our backlog. Thanks for your help - @gvwilson