Reputation: 167
I'm using openpyxl
module to plot the graphs for available analytical data. I'm able to plot the graphs, but I'm unable to find the option to change the font size of chart title. By default it's giving '18' as font size. In openpyxl
there was openpyxl.Styles
module which has 'Font' option. Using that, we are able to change the font of data available in cells. But, not the font size of chart title. Can any one help on this...
Here is my code:
from openpyxl import Workbook
from openpyxl.styles import Style, Font
from openpyxl.chart import (
AreaChart,
Reference,
Series,
)
wb = Workbook()
ws = wb.active
rows = [
['Number', 'Batch 1', 'Batch 2'],
[2, 40, 30],
[3, 40, 25],
[4, 50, 30],
[5, 30, 10],
[6, 25, 5],
[7, 50, 10],
]
for row in rows:
ws.append(row)
chart = AreaChart()
chart.title = "Area Chart"
chart.style = 20
chart.x_axis.title = 'Test'
chart.y_axis.title = 'Percentage'
chart.x_axis.Font = 10 -- /# Trying like this to change the font size. But throwing error #/
chart.y_axis.Font = 10
cats = Reference(ws, min_col=1, min_row=1, max_row=7)
data = Reference(ws, min_col=2, min_row=1, max_col=3, max_row=7)
chart.add_data(data, titles_from_data=True)
chart.set_categories(cats)
ws.add_chart(chart, "A10")
wb.save("area.xlsx")
Please help me in this regard
Upvotes: 0
Views: 2692
Reputation: 11
This worked for me for sure. I used this successfully in my own project
from openpyxl.chart.text import RichText
from openpyxl.drawing.text import Paragraph, ParagraphProperties, CharacterProperties, Font
font = Font(typeface='Arial')
cp = CharacterProperties(latin=font, sz=800, b=False)
pp = ParagraphProperties(defRPr=cp)
rtp = RichText(p=[Paragraph(pPr=pp, endParaRPr=cp)])
chart.x_axis.txPr = rtp
chart.y_axis.txPr = rtp
chart.y_axis.title.tx.rich.p[0].pPr = pp
chart.y_axis.title.tx.rich.p returns a list that contains various properties.The first element(=p[0]) contains pPr(=ParagraphProperties) which defines the font style of the title. You can assign your own custom pPr(=pp) with the style you want in this way
chart.y_axis.title.tx.rich.p[0].pPr = pp
Upvotes: 1
Reputation: 31
Here is another solution, as the older answer (and other ones on here) did not work in my case:
from openpyxl.drawing.text import Paragraph, ParagraphProperties, CharacterProperties, RichTextProperties, Font, RegularTextRun
chart.title.text.rich.paragraphs[0].pPr = ParagraphProperties(defRPr=CharacterProperties(
latin=Font(typeface='Tahoma'), sz=1000, b=True))
There is more info in the source code of the responsible module - "openpyxl.chart.title", look for function "title_maker(text)".
Sources: openpyxl docs, example from python-forum
Upvotes: 0
Reputation: 31
Try the following snippet with applying CharacterProperties
with integer sz
(size) value:
from openpyxl.drawing.text import CharacterProperties
chart.x_axis.title.tx.rich.p[0].r.rPr = CharacterProperties(sz=3500)
Upvotes: 3