How to show only one data label in excel chart using openpyxl? - python

I've the following code creating a simple excel sheet and a chart using openpyxl (code is from the documentation - edited to explain the need)
from datetime import date
from openpyxl import Workbook
from openpyxl.chart import (
LineChart,
Reference,
)
from openpyxl.chart.axis import DateAxis
from openpyxl.chart.label import DataLabelList
wb = Workbook()
ws = wb.active
rows = [
['Date', 'Batch 1', 'Batch 2', 'Batch 3'],
[date(2015,9, 1), 41, 30, 25],
[date(2015,9, 2), 41, 25, 30],
[date(2015,9, 3), 41, 30, 45],
[date(2015,9, 4), 41, 25, 40],
[date(2015,9, 5), 41, 35, 30],
[date(2015,9, 6), 41, 40, 35],
]
for row in rows:
ws.append(row)
c1 = LineChart()
c1.title = "Line Chart"
c1.style = 13
c1.y_axis.title = 'Size'
c1.x_axis.title = 'Test Number'
data = Reference(ws, min_col=2, min_row=1, max_col=4, max_row=7)
c1.add_data(data, titles_from_data=True)
s2 = c1.series[2]
s2.smooth = True # Make the line smooth
c1.dataLabels = DataLabelList()
###########################################################
#Display data label and series name
#I need this to be displayed only for the first data point
#I can do this in excel by displaying the label only for the
#data point required
c1.dataLabels.showVal = True
c1.dataLabels.showSerName = True
ws.add_chart(c1, "A10")
wb.save("line.xlsx")
Chart I'm getting
Chart I want - how can I get the chart like this?
Displaying label (series name and value) only for one data point...

I got this working and here is the code with explanation:
from datetime import date
from openpyxl import Workbook
from openpyxl.chart import (
LineChart,
Reference,
)
from openpyxl.chart.axis import DateAxis
from openpyxl.chart.label import DataLabelList
from openpyxl.chart.label import DataLabel
wb = Workbook()
ws = wb.active
rows = [
['Date', 'Batch 1', 'Batch 2', 'Batch 3'],
[date(2015,9, 1), 41, 30, 25],
[date(2015,9, 2), 41, 25, 30],
[date(2015,9, 3), 41, 30, 45],
[date(2015,9, 4), 41, 25, 40],
[date(2015,9, 5), 41, 35, 30],
[date(2015,9, 6), 41, 40, 35],
]
for row in rows:
ws.append(row)
c1 = LineChart()
c1.title = "Line Chart"
c1.style = 13
c1.y_axis.title = 'Size'
c1.x_axis.title = 'Test Number'
data = Reference(ws, min_col=2, min_row=1, max_col=4, max_row=7)
c1.add_data(data, titles_from_data=True)
#Get the first series
s1 = c1.series[0]
#Initialize data lables
s1.dLbls = DataLabelList()
#Initialize data label
dl = DataLabel()
#Set properties
dl.showVal = True
dl.showSerName = True
#position t for top
dl.position = "t"
#Append data label to data lebels
s1.dLbls.dLbl.append(dl)
#This produces expected result
ws.add_chart(c1, "A10")
wb.save("line.xlsx")
Result
Still I couldn't get the label text properties set!

Related

Exporting a pandas dataframe to excel using xlwings

import xlwings as xw
import pandas as pd
I'm trying to export a df into a specific sheet on excel I'm getting the following error:
self._oleobj_.Invoke(*(args + (value,) + defArgs))
TypeError: Objects for SAFEARRAYS must be sequences (of sequences), or a buffer object.
This is a simplified version of my DataFrame
df=pd.DataFrame(
{
'Color': ['red','blue','red','red','green','red','yellow'],
'Type': ['Oil', 'Aluminium', 'Oil', 'Oil', 'Cement Paint', 'Synthetic Rubber', 'Emulsion'],
'Finish' : ['Satin', 'Matte', 'Matte', 'Satin', 'Semi-gloss', 'Satin', 'Satin'],
'Use' : ['Interior', 'Exterior', 'Interior', 'Interior', 'Exterior', 'Exterior', 'Exterior'],
'Price' : [55, 75, 60, 60, 55, 75, 50]
}
)
Here's my code:
df = df.loc[(df['Price'] == 55) & (df['Color'] == 'red')]
df1 = df.loc[(df['Price'] == 55) & (df['Color'] == 'blue')]
df2 = df.loc[(df['Price'] == 55) & (df['Color'] == 'yellow') & (df['Color'] == 'green')]
# Load Wookbook
app = xw.App(visible = False)
wb = xw.Book(File_path)
Sheet1 = wb.sheets['Sheet1']
Sheet2 = wb.sheets['Sheet2']
Sheet3 = wb.sheets['Sheet3']
#Write data into Workbook
Sheet1.range('A1').options(index=False, header=False ).value = df
Sheet2.range('A1').options(index=False, header=False ).value = df2
Sheet3.range('A1').options(index=False, header=False ).value = df2
#Save data in Workbook and close wb
LPLwb.save()
LPLwb.close()
LPLapp.quit()
The end goal is to be able to export the different dfs into the specific sheets. I've done this before with no issue, but now I'm getting an odd error I had never gotten before. Googled it for a while but found nothing.
Any direction would be highly appreciated! Thanks

How to make labels visible inside the pie in openpyxl

I automate some task with openpyxl with xlsx file, i created a piechart but i want the piechart to show the labels and not only the value ( got exemple apple, cherry… will be in text inside the pie is there a way to do that with openpyxl ?
Thanks
from openpyxl import Workbook
from openpyxl.chart import (
PieChart,
ProjectedPieChart,
Reference
)
from openpyxl.chart.series import DataPoint
data = [
['Pie', 'Sold'],
['Apple', 50],
['Cherry', 30],
['Pumpkin', 10],
['Chocolate', 40],
]
wb = Workbook()
ws = wb.active
for row in data:
ws.append(row)
pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
pie.title = "Pies sold by category"
Do you want to do something like this where name and percent is marked on the segments?
from openpyxl import Workbook
from openpyxl.chart.label import DataLabelList
from openpyxl.chart import (
PieChart,
Reference
)
data = [
['Pie', 'Sold'],
['Apple', 50],
['Cherry', 30],
['Pumpkin', 10],
['Chocolate', 40],
]
wb = Workbook()
ws = wb.active
for row in data:
ws.append(row)
pie = PieChart()
labels = Reference(ws, min_col=1, min_row=2, max_row=5)
data = Reference(ws, min_col=2, min_row=1, max_row=5)
pie.add_data(data, titles_from_data=True)
pie.set_categories(labels)
pie.title = "Pies sold by category"
### Add Label into chart
pie.dataLabels = DataLabelList()
pie.dataLabels.showPercent = True
pie.dataLabels.showCatName = True
ws.add_chart(pie, "A10")
wb.save('test_chart.xlsx')
It should produce a chart like

Altair word map filtering by years not working

I have a problem with filtering data based on 'year' column values. I have a drop-down with every year starting from 1950 to 2013, and when I change the value in the dropdown map should rerender with new data, but it doesn't. The map only renders for 2013 year (last group in dataset).
Here is code:
years = pd.unique(seasonData['year'])
seasons = ['yearAvg', 'summerAvg', 'winterAvg']
#map selector
selectorYear = alt.selection_single(
name='Years',
fields=['year'],
bind=alt.binding_select(options=years, name="Year"),
init={'year': '1951'},
)
selectorSeason = alt.selection_single(
name='Temperature for',
fields=['column'],
bind=alt.binding_select(options=seasons, name="Seasons"),
init={'column': 'yearAvg'},
)
base = alt.Chart(geoDF).mark_geoshape(
fill = '#bfdff7', stroke = 'white', strokeWidth = 1
).transform_lookup(
lookup='name_long',
from_= alt.LookupData(seasonData, 'Country', ['yearAvg', 'summerAvg', 'winterAvg', 'year', 'Country'])
).transform_fold(
seasons, as_ = ['column', 'value']
).encode(
tooltip = [alt.Tooltip('value:Q', title='Temperature', format='.2f'), alt.Tooltip('Country:N', title='Country'), alt.Tooltip('year:N', title='year')], #-40, -20, 0, 5, 10, 15, 20, 25, 30, 35, 40, 50
fill = alt.Fill('value:Q', title='Avarage temperature by county', scale=alt.Scale(type="linear", domain=[-40, -20, 0, 5, 10, 15, 20, 25, 30, 35, 40, 50], range=['#00f', '#2424f7', '#2ad8ff', '#8fe0ff', '#f3ff8f', '#fff18f', '#ffc254', '#ff9354', '#ff6c54', '#fd553a', '#fd1a1a', '#f00'] ))
).add_selection(
selectorYear,
selectorSeason
).transform_filter(
selectorYear & selectorSeason
).properties(
width = 1000, height = 650,
title='World map of temperature data (1950 - 2013)'
)
base
Here is how data looks:
Here is how the chart looks:
And if I change year in the dropdown the chart goes black.
What am I doing wrong? How can I fix this?
The solution described in a comment from #jakevdp works. Just change data frame passed to the chart function with data frame passed to LookupData like so:
base = alt.Chart(seasonData).mark_geoshape(
fill = '#bfdff7', stroke = 'white', strokeWidth = 1
).transform_lookup(
lookup='Country',
# from_= alt.LookupData(seasonData, 'Country', ['yearAvg', 'summerAvg', 'winterAvg', 'year', 'Country'])
from_= alt.LookupData(geoDF, 'name_long', ['scalerank', ...... , 'geometry'])
)
But for proper rendering, I needed to include (fields argument of LookupData function) all fields from geo df. Adding only geometry doesn't work.

Problem with visualization with Python Plotly Pandas?

I have Pandas data frame like this: data = pd.DataFrame({"Risk":["good", "bad", "good", "good", "bad"], "Age":[22, 50, 43, 27, 19]})
and I wan to achieve something like this:
Why my code does not work ? Could you repare my code? I have error that: AttributeError: 'list' object has no attribute 'loc'
import plotly.graph_objects as go
import plotly.tools as tls
import chart_studio.plotly as py
df_good = data.loc[data["Risk"] == 'good']['Age'].values.tolist()
df_bad = data.loc[data["Risk"] == 'bad']['Age'].values.tolist()
df_age = data['Age'].values.tolist()
#First plot
trace0 = go.Histogram(
x=df_good,
histnorm='probability',
name="Good Credit"
)
#Second plot
trace1 = go.Histogram(
x=df_bad,
histnorm='probability',
name="Bad Credit"
)
#Third plot
trace2 = go.Histogram(
x=df_age,
histnorm='probability',
name="Overall Age"
)
#Creating the grid
fig = tls.make_subplots(rows=2, cols=2, specs=[[{}, {}], [{'colspan': 2}, None]],
subplot_titles=('Good','Bad', 'General Distribuition'))
#setting the figs
fig.append_trace(trace0, 1, 1)
fig.append_trace(trace1, 1, 2)
fig.append_trace(trace2, 2, 1)
fig['layout'].update(showlegend=True, title='Age Distribuition', bargap=0.05)
py.iplot(fig, filename='custom-sized-subplot-with-subplot-titles')

Python plot scikit-fuzzy not responding

Hello i tried to make fuzzy system by scikit-fuzzy, the output seems running well but when i try to figure it according scikit-fuzzy new api, my plot is not responding. I remember last time when I using scikit-fuzzy my plot is running well, whats wrong? Do my code is lack something?
import numpy as np
import skfuzzy as fuzz
from skfuzzy import control as ctrl
# crisp set
keramaian = ctrl.Antecedent(np.arange(0, 30, 1), 'KERAMAIAN')
ukuran = ctrl.Antecedent(np.arange(0, 25, 1), 'UKURAN')
vol = ctrl.Consequent(np.arange(0, 100, 1), 'UKURAN VOLUME')
# fuzzyfication
ukuran['Kecil'] = fuzz.trimf(ukuran.universe, [0, 0, 13])
ukuran['Sedang'] = fuzz.trimf(ukuran.universe, [0, 12, 24])
ukuran['Besar'] = fuzz.trimf(ukuran.universe, [12, 24, 24])
keramaian['sunyi'] = fuzz.trimf(keramaian.universe, [0, 0, 15])
keramaian['Cukup Ramai'] = fuzz.trimf(keramaian.universe, [0, 15, 29])
keramaian['Berisik'] = fuzz.trimf(keramaian.universe, [15, 29, 29])
vol['Pelan'] = fuzz.trimf(vol.universe, [0, 0, 40])
vol['Sedang'] = fuzz.trimf(vol.universe, [30, 50, 70])
vol['Kencang'] = fuzz.trimf(vol.universe, [60, 99, 99])
# rule set
rule1 = ctrl.Rule(ukuran['Kecil'] & keramaian['Berisik'], vol['Kencang'])
rule2 = ctrl.Rule(ukuran['Kecil'] & keramaian['Cukup Ramai'], vol['Kencang'])
rule3 = ctrl.Rule(ukuran['Kecil'] & keramaian['Cukup Ramai'], vol['Kencang'])
rule4 = ctrl.Rule(ukuran['Sedang'] & keramaian['Berisik'], vol['Sedang'])
rule5 = ctrl.Rule(ukuran['Sedang'] & keramaian['Cukup Ramai'], vol['Sedang'])
rule6 = ctrl.Rule(ukuran['Sedang'] & keramaian['sunyi'], vol['Sedang'])
rule7 = ctrl.Rule(ukuran['Besar'] & keramaian['Berisik'], vol['Pelan'])
rule8 = ctrl.Rule(ukuran['Besar'] & keramaian['Cukup Ramai'], vol['Pelan'])
rule9 = ctrl.Rule(ukuran['Besar'] & keramaian['sunyi'], vol['Pelan'])
vol_suara_ctrl = ctrl.ControlSystem([rule1, rule2, rule3, rule4, rule5, rule6, rule7, rule8, rule9])
vol_suara = ctrl.ControlSystemSimulation(vol_suara_ctrl)
keramaian['sunyi'].view()
vol_suara.input['KERAMAIAN'] = int(input("Masukkan jumlah keramaian?\n"))
vol_suara.input['UKURAN'] = int(input("Masukkan ukuran speaker?\n"))
# defuzification
vol_suara.compute()
vol.view(sim=vol_suara)
print(vol_suara.output['UKURAN VOLUME'])
Import import matplotlib.pyplot as plt
And try to use plt.show() at the end of your code.

Categories