How to set order of the nodes in Sankey Diagram Plotly - python

So i am traying to make a cycle that gives different sankey diagram the thing is due to the plotly optimization the node are in different positions. I will like to set the standard order to be [Formal, Informal, Unemployed, Inactive]
import matplotlib.pyplot as plt
import pandas as pd
import plotly.graph_objects as go
df = pd.read_csv(path, delimiter=",")
Lista_Paises = df["code"].unique().tolist()
Lista_DF = []
for x in Lista_Paises:
DF_x = df[df["code"] == x]
Lista_DF.append(DF_x)
def grafico(df):
df = df.astype({"Source": "category", "Value": "float", "Target": "category"})
def category(i):
if i == "Formal":
return 0
if i == "Informal":
return 1
if i == "Unemployed":
return 2
if i == "Inactive":
return 3
def color(i):
if i == "Formal":
return "#9FB5D5"
if i == "Informal":
return "#E3EEF9"
if i == "Unemployed":
return "#E298AE"
if i == "Inactive":
return "#FCEFBC"
df['Source_cat'] = df["Source"].apply(category).astype("int")
df['Target_cat'] = df["Target"].apply(category).astype("int")
# df['Source_cat'] = LabelEncoder().fit_transform(df.Source)
# df['Target_cat'] = LabelEncoder().fit_transform(df.Target)
df["Color"] = df["Source"].apply(color).astype("str")
df = df.sort_values(by=["Source_cat", "Target_cat"])
Lista_Para_Sumar = df["Source_cat"].nunique()
Lista_Para_Tags = df["Source"].unique().tolist()
Suma = Lista_Para_Sumar
df["out"] = df["Target_cat"] + Suma
TAGS = Lista_Para_Tags + Lista_Para_Tags
Origen = df['Source_cat'].tolist()
Destino = df["out"].tolist()
Valor = df["Value"].tolist()
Color = df["Color"].tolist()
return (TAGS, Origen, Destino, Valor, Color)
def Sankey(TAGS: object, Origen: object, Destino: object, Valor: object, Color: object, titulo: str) -> object:
label = TAGS
source = Origen
target = Destino
value = Valor
link = dict(source=source, target=target, value=value,
color=Color)
node = dict(x=[0, 0, 0, 0, 1, 1, 1, 1], y=[1, 0.75, 0.5, 0.25, 0, 1, 0.75, 0.5, 0.25, 0], label=label, pad=35,
thickness=10,
color=["#305CA3", "#C1DAF1", "#C9304E", "#F7DC70", "#305CA3", "#C1DAF1", "#C9304E", "#F7DC70"])
data = go.Sankey(link=link, node=node, arrangement='snap')
fig = go.Figure(data)
fig.update_layout(title_text=titulo + "-" + "Mujeres", font_size=10, )
plt.plot(alpha=0.01)
titulo_guardar = (str(titulo) + ".png")
fig.write_image("/Users/agudelo/Desktop/GRAFICOS PNUD/Graficas/MUJERES/" + titulo_guardar, engine="kaleido")
for y in Lista_DF:
TAGS, Origen, Destino, Valor, Color = grafico(y)
titulo = str(y["code"].unique())
titulo = titulo.replace("[", "")
titulo = titulo.replace("]", "")
titulo = titulo.replace("'", "")
Sankey(TAGS, Origen, Destino, Valor, Color, titulo)
The expected result should be.
The expected result due to the correct order:
The real result i am getting is:

I had a similar problem earlier. I hope this will work for you. As I did not have your data, I created some dummy data. Sorry about the looooong explanation. Here are the steps that should help you reach your goal...
This is what I did:
Order the data and sort it - used pd.Categorical to set the order and then df.sort to sort the data so that the input is sorted by source and then destination.
For the sankey node, you need to set the x and y positions. x=0, y=0 starts at top left. This is important as you are telling plotly the order you want the nodes. One weird thing is that it sometimes errors if x or y is at 0 or 1. Keep it very close, but not the same number... wish I knew why
For the other x and y entries, I used ratios as my total adds up to 285. For eg. Source-Informal starts at x = 0.001 and y = 75/285 as Source-Formal = 75 and this will start right after that
Based on step 1, the link -> source and destination should also be sorted. But, pls do check.
Note: I didn't color the links, but think you already have achieved that...
Hope this helps resolve your issue...
My data - sankey.csv
source,destination,value
Formal,Formal,20
Formal,Informal, 10
Formal,Unemployed,30
Formal,Inactive,15
Informal,Formal,20
Informal,Informal,15
Informal,Unemployed,25
Informal,Inactive,25
Unemployed,Formal,5
Unemployed,Informal,10
Unemployed,Unemployed,10
Unemployed,Inactive,5
Inactive,Formal,30
Inactive,Informal,20
Inactive,Unemployed,20
Inactive,Inactive,25
The code
import plotly.graph_objects as go
import pandas as pd
df = pd.read_csv('sankey.csv') #Read above CSV
#Sort by Source and then Destination
df['source'] = pd.Categorical(df['source'], ['Formal','Informal', 'Unemployed', 'Inactive'])
df['destination'] = pd.Categorical(df['destination'], ['Formal','Informal', 'Unemployed', 'Inactive'])
df.sort_values(['source', 'destination'], inplace = True)
df.reset_index(drop=True)
mynode = dict(
pad = 15,
thickness = 20,
line = dict(color = "black", width = 0.5),
label = ['Formal', 'Informal', 'Unemployed', 'Inactive', 'Formal', 'Informal', 'Unemployed', 'Inactive'],
x = [0.001, 0.001, 0.001, 0.001, 0.999, 0.999, 0.999, 0.999],
y = [0.001, 75/285, 160/285, 190/285, 0.001, 75/285, 130/285, 215/285],
color = ["#305CA3", "#C1DAF1", "#C9304E", "#F7DC70", "#305CA3", "#C1DAF1", "#C9304E", "#F7DC70"])
mylink = dict(
source = [ 0, 0, 0, 0, 1, 1, 1, 1, 2, 2, 2, 2, 3, 3, 3, 3 ],
target = [ 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7, 4, 5, 6, 7 ],
value = df.value.to_list())
fig = go.Figure(data=[go.Sankey(
arrangement='snap',
node = mynode,
link = mylink
)])
fig.update_layout(title_text="Basic Sankey Diagram", font_size=20)
fig.show()
The output

Related

labeling Confidence interval and coefficient using ggplot in Pandas

I tried to label coefficient and Confidence interval using the following code:
pp =p.ggplot(leadslags_plot, p.aes(x = 'label', y = 'mean',
ymin = 'lb',
ymax = 'ub')) +\
p.geom_line(p.aes(group = 1),color = "b") +\
p.geom_pointrange(color = "b",size = 0.5) +\
p.geom_errorbar(color = "r", width = 0.2) +\
p.scale_color_manual(name= "label:", values = ['b','r'],labels = ["coeff","95 percent CI"] )+\
p.theme("bottom") +\
p.xlab("Years before and after ") +\
p.ylab("value ") +\
p.geom_hline(yintercept = 0,
linetype = "dashed") +\
p.geom_vline(xintercept = 0,
linetype = "dashed")
the code generates the plot but does not label the 'coeff' and 'CI'. How can I label 'coeff' and 'CI'
The issue is that to get a legend you have to map on aesthetics. In ggplot2 (the R one) this could be easily achieved by moving color="b" inside aes() which however does not work in plotnine or Python. Maybe there is a more pythonistic way to get around this issue but one option would be to add two helper columns to your dataset which could then be mapped on the color aes:
import pandas as pd
import plotnine as p
leadslags_plot = [[-2, 1, 0, 2], [0, 2, 1, 3], [2, 3, 2, 4]]
leadslags_plot = pd.DataFrame(leadslags_plot, columns=['label', 'mean', 'lb', 'ub'])
leadslags_plot["b"] = "b"
leadslags_plot["r"] = "r"
(p.ggplot(leadslags_plot, p.aes(x = 'label', y = 'mean',
ymin = 'lb',
ymax = 'ub')) +\
p.geom_line(p.aes(group = 1),color = "b") +\
p.geom_pointrange(p.aes(color = "b"),size = 0.5) +\
p.geom_errorbar(p.aes(color = "r"), width = 0.2) +\
p.scale_color_manual(name= "label:", values = ['b','r'], labels = ["coeff", "95 percent CI"] )+\
p.theme("bottom", subplots_adjust={'right': 0.8}) +\
p.xlab("Years before and after ") +\
p.ylab("value ") +\
p.geom_hline(yintercept = 0,
linetype = "dashed") +\
p.geom_vline(xintercept = 0,
linetype = "dashed"))

Matplotlib: center Y-axis on 0

I've made a function to graph economic performance, but the output is often lopsided on the y-axis.
The below graph shows the problem. The range of y values makes the chart default to the max/min as the range of the y axis.
Is there any way to force the chart to center itself on 0, or do I need derive the max and min y values within the function?
The function is below. If you'd like me to replace the variables with values to repro the chart lmk- it's a bit of a task.
def recession_comparison(key, variable, dimension):
'''
Creates the "scary chart"- proportional growth for a single area/industry. All recessions included in chart.
Parameters:
key (str or int): area-fips or industry_code
variable (str): determines what economic indicator will be used in the timeline. Must be one of ['month3_emplvl' (employment), 'avg_wkly_wage' (wages), 'qtrly_estabs_count'(firms)]
dimension (str): dimension of data to chart.
Returns:
fig (matplotlib plot)
'''
fig, ax = plt.subplots(figsize =(15, 10))
if dimension == 'area':
index = 'area_fips'
title = 'Recession Comparison, ' + area_titles[key] + " (" + str(key) + ")"
elif dimension == 'industry':
index = 'industry_code'
title = 'Recession Comparison: ' + industry_titles[key] + " (" + str(key) + ")"
for recession in recessions_int.keys():
if recession == 'full':
break
loadpath = filepath(variable = variable, dimension = dimension, charttype = 'proportional', recession = recession, filetype = 'json')
df = pd.read_json(loadpath)
df.set_index(index, inplace = True)
ax.plot(df.loc[key][1:-1]*100, label = str(recession), linewidth = 1.5, alpha = 0.8)
ax.axvline(x = 6, color = 'black', linewidth = 0.8, alpha = 0.5, ls = ':', label = 'Event Quarter')
ax.axhline(y = 0, color = 'black', linewidth = 0.8, alpha = 0.5, ls = '--', label = 'Pre-Recession baseline')
ax.set_xlabel('Quarters since start of recession')
ax.set_ylabel('Growth: ' + var_display[variable])
ax.set_title(title)
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.legend()
plt.show()
return fig
edit: full code solution from DapperDuck:
def recession_comparison(key, variable, dimension):
fig, ax = plt.subplots(figsize =(15, 10))
if dimension == 'area':
index = 'area_fips'
title = 'Recession Comparison, ' + area_titles[key] + " (" + str(key) + ")"
elif dimension == 'industry':
index = 'industry_code'
title = 'Recession Comparison: ' + industry_titles[key] + " (" + str(key) + ")"
for recession in recessions_int.keys():
if recession == 'full':
break
loadpath = filepath(variable = variable, dimension = dimension, charttype = 'proportional', recession = recession, filetype = 'json')
df = pd.read_json(loadpath)
df.set_index(index, inplace = True)
ax.plot(df.loc[key][1:-1]*100, label = str(recession), linewidth = 1.5, alpha = 0.8)
ax.axvline(x = 6, color = 'black', linewidth = 0.8, alpha = 0.5, ls = ':', label = 'Event Quarter')
ax.axhline(y = 0, color = 'black', linewidth = 0.8, alpha = 0.5, ls = '--', label = 'Pre-Recession baseline')
yabs_max = abs(max(ax.get_ylim(), key=abs))
ax.set_ylim(ymin=-yabs_max, ymax=yabs_max)
ax.set_xlabel('Quarters since start of recession')
ax.set_ylabel('Growth: ' + var_display[variable])
ax.set_title(title)
ax.yaxis.set_major_formatter(mtick.PercentFormatter())
plt.legend()
plt.show()
return fig
Corrected image:
Add the following code right after ax.axhline(y = 0, color = 'black', linewidth = 0.8, alpha = 0.5, ls = '--', label = 'Pre-Recession baseline'):
yabs_max = abs(max(ax.get_ylim(), key=abs))
ax.set_ylim(ymin=-yabs_max, ymax=yabs_max)

Plotly: How to use both dollar signs and linebreaks in annotations?

Not sure if I'm missing something obvious here but when I'm inserting a break (<br>) into my text with annotations it just seems to ignore it. I've tried fig.add_annotations but the same thing happens.
Do you know why this isn't working?
import pandas as pd
import plotly.graph_objects as go
import numpy as np
df = pd.DataFrame({"Growth_Type": ["Growing Fast", "Growing", "Stable", "Dropping", "Dropping Fast"],
"Accounts": [407,1275,3785,1467,623],
"Gain_Share": [1.20,8.1,34.4,6.5,0.4],
"Keep_Share": [16.5, 101.2, 306.3, 107.2, 27.7]})
df2 = pd.concat([pd.DataFrame({"Growth_Type":df["Growth_Type"],
"Opportunity_Type": np.repeat("Gain Share", 5),
"Wallet_Share": df["Gain_Share"]}),
pd.DataFrame({"Growth_Type":df["Growth_Type"],
"Opportunity_Type": np.repeat("Keep Share", 5),
"Wallet_Share": df["Keep_Share"]})])
fig = go.Figure()
fig.add_trace(go.Bar(x = df2["Wallet_Share"],
y = df2["Growth_Type"],
orientation = "h"
))
fig.update_layout(font = dict(size = 12, color = "#A6ACAF"),
xaxis_tickprefix = "$",
plot_bgcolor = "white",
barmode = "stack",
margin = dict(l = 150,
r = 250,
b = 100,
t = 100),
annotations = [dict(text = 'Dropping presents a gain share<br>opportunity of $6.5 mill and a<br>keep share opportunity of $34.4 mill',
xref = "x",
yref = "y",
x = 360,
y = "Dropping",
showarrow = False,
yanchor = "bottom")]
)
fig.show()
It's not the linebreaks that are causing the trouble here; it is the dollar sign.
But you can use the printable ASCII character '$'to get what you want instead:
text = 'Dropping presents a gain share<br>opportunity of '+ '$'+ '6.5 mill and a<br>keep share opportunity of ' + '$'+ '34.4 mill'
Plot:
Complete code:
import pandas as pd
import plotly.graph_objects as go
import numpy as np
df = pd.DataFrame({"Growth_Type": ["Growing Fast", "Growing", "Stable", "Dropping", "Dropping Fast"],
"Accounts": [407,1275,3785,1467,623],
"Gain_Share": [1.20,8.1,34.4,6.5,0.4],
"Keep_Share": [16.5, 101.2, 306.3, 107.2, 27.7]})
df2 = pd.concat([pd.DataFrame({"Growth_Type":df["Growth_Type"],
"Opportunity_Type": np.repeat("Gain Share", 5),
"Wallet_Share": df["Gain_Share"]}),
pd.DataFrame({"Growth_Type":df["Growth_Type"],
"Opportunity_Type": np.repeat("Keep Share", 5),
"Wallet_Share": df["Keep_Share"]})])
fig = go.Figure()
fig.add_trace(go.Bar(x = df2["Wallet_Share"],
y = df2["Growth_Type"],
orientation = "h"
))
fig.update_layout(font = dict(size = 12, color = "#A6ACAF"),
xaxis_tickprefix = "$",
plot_bgcolor = "white",
barmode = "stack",
margin = dict(l = 150,
r = 250,
b = 100,
t = 100),
annotations = [dict(text = 'Dropping presents a gain share<br>opportunity of '+ '$'+ '6.5 mill and a<br>keep share opportunity of ' + '$'+ '34.4 mill',
#annotations = [dict(text = '$',
xref = "x",
yref = "y",
x = 360,
y = "Dropping",
showarrow = False,
yanchor = "bottom")]
)
fig.show()

braidTool_Maya_script_error # NameError: name 'QtGui' is not defined

I found someone else's braid tool online and it seems to be working for other people but it doesn't for me. I can't reach that person for help so I am posting here instead.
There's 2 scripts, one is the actual making of the braid and the other is for loading UI. I keep getting The following error:
# Error: Traceback (most recent call last):
# File "<maya console>", line 2, in <module>
# File "/home/ykim/private/maya/2018/scripts/JUM/scripts/braid.py", line 12, in <module>
# list_form, list_base = load_ui_type(ui_file)
# File "/home/ykim/private/maya/2018/scripts/JUM/core/loadUIFile.py", line 30, in load_ui_type
# form_class = frame['Ui_{0}'.format(form_class)]
# File "<string>", line 1, in <module>
# NameError: name 'QtGui' is not defined
#
The following is the 1st script making the braid
import os
from JUM.core.loadUIFile import get_maya_window, load_ui_type
import random
import maya.cmds as cmds
ui_file = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'UI','braid.ui')
list_form, list_base = load_ui_type(ui_file)
class espiral(list_form, list_base):
def __init__(self, parent = get_maya_window()):
self.__radius = 0.0
self.__side = 6
self.__variation = 0
self.__circle = ''
self.__pt_position_A = []
self.__pt_position_B = []
self.__pt_position_C = []
self.__path = ''
self.__quantidade = 0.0
self.clock = True
##########################################################
# #
# UI elements #
# #
##########################################################
self.window_name = 'makeSpiralWin'
if cmds.window(self.window_name, exists = True):
cmds.deleteUI(self.window_name)
super(espiral, self).__init__(parent)
self.setupUi(self)
self.btn_selectPath.clicked.connect(self.getPath)
self.btn_create.setDisabled(True)
self.btn_create.clicked.connect(self.create)
def __makeEight(self):
side = 16
offset = self.spin_offset.value()
eight = cmds.circle(nr=(0, 1, 0), c=(0, 0, 0), degree=3, sections=side)
cmds.select(eight[0])
lattice = cmds.lattice(dv = (3, 2, 3), objectCentered = True )
cmds.setAttr(lattice[0]+'.local', 0)
cmds.select(lattice[1]+'.pt[2][0:1][0]',lattice[1]+'.pt[2][0:1][1]',lattice[1]+'.pt[2][0:1][2]')
cmds.scale(1, 1, -1, pivot = (1.108194, 0 , 0), relative = True)
cmds.select(lattice[1]+'.pt[1][0:1][0]',lattice[1]+'.pt[1][0:1][1]',lattice[1]+'.pt[1][0:1][2]')
cmds.scale(0, 0, 0, pivot = (0, 0 , 0), relative = True)
cmds.select(lattice[1]+'.pt[0][0:1][0]',lattice[1]+'.pt[2][0:1][2]',lattice[1]+'.pt[2][0:1][0]',lattice[1]+'.pt[0][0:1][2]')
cmds.scale(1, 1, 1.455556, pivot = (0, 0 , 0), relative = True)
cmds.scale(0.929167, 1, 1, pivot = (0, 0 , 0), relative = True)
cmds.select(eight[0])
cmds.delete(ch = True)
cmds.rotate(0,offset,0,eight[0])
cmds.makeIdentity(eight[0],apply = True, t = True, r = True, s = True, n = 0, pn = True)
return eight
def __next(self, porcentagem,eight,scale):
#print porcentagem
curva = self.ln_path.text()
position = cmds.pointOnCurve(curva, top=True, pr=porcentagem, position=True)
tangent = cmds.pointOnCurve(curva, top=True, pr=porcentagem, tangent=True)
angle = cmds.angleBetween(er=True, v1=(0.0, 1.0, 0.0), v2=tangent)
cmds.scale((scale * random.uniform((1-self.spin_random.value()), 1.0)),
(scale * random.uniform((1-self.spin_random.value()), 1.0)),
(scale * random.uniform((1-self.spin_random.value()), 1.0)),
eight[0])
cmds.move(position[0],
position[1],
position[2],
eight[0])
cmds.rotate(angle[0],
angle[1],
angle[2],
eight[0])
def __voltas(self):
steps = 16 * float(self.spin_loops.value())
porcent = 1.0 / steps
return int(steps), porcent
def __makeMesh(self,curva):
scale_0 = self.spin_radius.value()
scale_1 = self.spin_radius_1.value()
scale = self.spin_radius.value()
if (scale_0 >= scale_1):
tempMaior = scale_0
tempMenor = scale_1
else:
tempMaior = scale_1
tempMenor = scale_0
scale_extrude = tempMenor/tempMaior
position = cmds.pointOnCurve(curva, top=True, pr=0, position=True)
tangent = cmds.pointOnCurve(curva, top=True, pr=0, normalizedTangent=True)
angle = cmds.angleBetween(er=True, v1=(0.0, 1.0, 0.0), v2=tangent)
circle = cmds.circle(nr=(0, 1, 0), c=(0, 0, 0), degree=3, sections=16, r = 0.5)
cmds.scale(tempMaior,
tempMaior,
tempMaior,
circle[0])
cmds.move(position[0],
position[1],
position[2],
circle[0])
cmds.rotate(angle[0],
angle[1],
angle[2],
circle[0])
extrude = cmds.extrude(circle[0],
curva,
constructionHistory = True,
range = True,
polygon = 0,
extrudeType = 2,
useComponentPivot = 0,
fixedPath = 0,
useProfileNormal = 1,
rotation = 0,
scale = scale_extrude,
reverseSurfaceIfPathReversed = 1)
poly = cmds.nurbsToPoly(extrude[0], matchNormalDir = True, constructionHistory = False, format = 2, polygonType = 1, uType = 3, uNumber = 1, vType = 3, vNumber = 3)
cmds.delete(circle, extrude[0])
print poly
return poly
def __curve(self):
curve_A = cmds.curve(p=self.__pt_position_A)
curve_B = cmds.curve(p=self.__pt_position_B)
curve_C = cmds.curve(p=self.__pt_position_C)
if (self.btn_makeMesh.isChecked()):
mesh_A = self.__makeMesh(curve_A)
mesh_B = self.__makeMesh(curve_B)
mesh_C = self.__makeMesh(curve_C)
cmds.delete(curve_A, curve_B, curve_C)
cmds.select(mesh_A,mesh_B,mesh_C)
else:
cmds.select(curve_A,curve_B,curve_C)
def __braid(self):
steps, porcent = self.__voltas()
increment = porcent
eight = self.__makeEight()
list = range(int(steps))
offset = self.spin_offset.value()
offset_normalize = offset/360.0
self.progress_Create.setRange(0,len(list))
scale_0 = self.spin_radius.value()
scale_1 = self.spin_radius_1.value()
if (scale_0 >= scale_1):
scale_maior = scale_0
scale_menor = scale_1
else:
scale_maior = scale_1
scale_menor = scale_0
diference = scale_maior-scale_menor
percent = diference/steps
scale = scale_maior
if (self.btn_reverse.isChecked()):
curva = self.ln_path.text()
cmds.reverseCurve(curva,ch = False, replaceOriginal = True)
for i in list:
self.progress_Create.setValue(i)
self.__next(porcent,eight,scale)
porcent += increment
_pos_A = (i*0.0625)%1.0 + offset_normalize
_pos_B = (i*0.0625+0.333333)%1.0 + offset_normalize
_pos_C = (i*0.0625+0.666666666)%1.0 + offset_normalize
self.__pt_position_A.append(cmds.pointOnCurve( eight[0],top = True, pr= _pos_A, p=True ))
self.__pt_position_B.append(cmds.pointOnCurve( eight[0],top = True, pr= _pos_B, p=True ))
self.__pt_position_C.append(cmds.pointOnCurve( eight[0],top = True, pr= _pos_C, p=True ))
scale -= percent
self.progress_Create.reset()
#cmds.delete(self.__circle[0])
# return self.__pt_position
self.__curve()
cmds.delete(eight[0])
def getPath(self):
path = cmds.ls(sl = True)
if path == []:
self.ln_path.setText('Nothing selected')
self.btn_create.setDisabled(True)
self.ln_path.setStyleSheet("background-color: rgb(110, 90, 90);")
else:
shape_path = cmds.listRelatives(path[0])
if (cmds.objectType(shape_path)== 'nurbsCurve'):
self.ln_path.setText(path[0])
self.btn_create.setEnabled(True)
self.ln_path.setStyleSheet("background-color: rgb(90, 150, 50);")
else:
self.ln_path.setText('Path not valid')
self.btn_create.setDisabled(True)
self.ln_path.setStyleSheet("background-color: rgb(110, 90, 90);")
def create(self):
self.__braid()
self.__pt_position_A = []
self.__pt_position_B = []
self.__pt_position_C = []
def run():
espira = espiral()
espira.show()
Another script is for loading UI design
import shiboken2
from PySide2 import QtWidgets
from PySide2 import QtGui
import maya.OpenMayaUI as apiUI
from cStringIO import StringIO
import pyside2uic
import xml.etree.ElementTree as xml
def get_maya_window():
ptr = apiUI.MQtUtil.mainWindow()
if ptr is not None:
return shiboken.wrapInstance(long(ptr), QtGui.QMainWindow)
def load_ui_type(ui_file):
parsed = xml.parse(ui_file)
widget_class = parsed.find('widget').get('class')
form_class = parsed.find('class').text
with open(ui_file,'r') as f:
o = StringIO()
frame = {}
pysideu2ic.compileUi(f, o, indent = 0)
pyc = compile(o.getvalue(), '<string>', 'exec')
exec pyc in frame
# Fetch the base_class and form class based on their type in the xml from design
form_class = frame['Ui_{0}'.format(form_class)]
base_class = eval('QtGui.{0}'.format(widget_class))
return form_class, base_class

I want to create a genric format function, what is default value of top,bottom,right,left

def columnandcellformate(sheet_name,bold = 0,font_color = '#000000',bg_color = '#ffffff',align = '' ,bottom = 0 ,top = 3,right = 0,left = 0,font_size = 10 ,starcolumn = 0, endrow = 0 ):
global sheet_format
sheet_format=sheet_name.add_format({
'bottom':bottom,
'top' : top,
'bg_color':bg_color,
'font_color' : font_color,
'align':align,
'font_size':font_size,
'bold': bold,
'font_name':'Batang'
})
What is default value of top,bottom,right,left, My function is making cell top,bottom,right and left blank
I think your default background color may have been causing some issues with the cell borders. I've added a few conditions based on whether you want these called by your function or not. These conditions make use of Format Methods such as format.set_bg_color(), format.set_bottom() (see docs for more information on these). They only provide a background color if you change it from the default.
import xlsxwriter
def columnandcellformate(bold = 0, font_color = '#000000', bg_color = 'none', align = '' , bottom = 999, top = 999, right = 999, left = 999, font_size = 10):
global sheet_format
sheet_format=workbook.add_format({
'font_color' : font_color,
'align': align,
'font_size': font_size,
'bold': bold,
'font_name': 'Batang'
})
if bg_color != 'none':
sheet_format.set_bg_color(bg_color)
if bottom != 999:
sheet_format.set_bottom(bottom)
if top != 999:
sheet_format.set_top(top)
if right != 999:
sheet_format.set_right(right)
if left != 999:
sheet_format.set_left(left)
workbook = xlsxwriter.Workbook('test.xlsx')
ws = workbook.add_worksheet('test_1')
columnandcellformate()
ws.write('B1', 'foo', sheet_format)
columnandcellformate(bold = 1, font_color = '#9C0006', bg_color = '#FFC7CE', align = '', bottom = 2, top = 1, right = 1, left = 1, font_size = 10)
ws.write('B3', 'bar', sheet_format)
workbook.close()
Expected Output:
The default values for format properties are almost all 0/False. See the initialization code for a format object.

Categories