Comparing Excel to learn openpyxl series to draw charts

Basic settings for charts


chart.title = "我是图表标题"
chart.y_axis.title = '我是y轴标题'
chart.x_axis.title = '我是x轴标题'
#图例设置
chart.legend=Legend(legendPos='r')
# 参数还有,l,r,t,b,tr,代表左侧,右侧,上方,下方,右上方

#图表样式
chart.style=1 #图表样式类型(1-48)

Specify the chart type

c1 = LineChart() #折线图
c1 = BarChart() #柱状图
c1 = AreaChart() #面积图
c1 = ScatterChart() #散点图
c1 = BubbleChart() #气泡图

other settings

二维数据
values = Reference(ws, min_col=1, min_row=1, max_col=1, max_row=10)#数据引用
#最小行在第1行,最小列在第1列,最大行在第10行,最大列在第1列,也就是把图表的数据给框起来了

三维数据如何添加,比如像气泡图等
#向空坐标系中添加数据
xvalues = Reference(ws, min_col=1, min_row=1, max_row=10)#x值
yvalues = Reference(ws, min_col=2, min_row=2, max_row=10)#y值
size = Reference(ws, min_col=3, min_row=1, max_row=10)#size值
series = Series(values=yvalues, xvalues=xvalues, zvalues=size)
c1.series.append(series)




ws.add_chart(chart, "B2")#添加图表

#将做好的图表的图片添加到 ws 中
ws.add_image(img, 'A1')

#对图片的宽和高进行设置
newsize = (90, 90)
img.width, img.height = newsize


case:

from openpyxl import Workbook
from openpyxl.chart import LineChart,Reference

#创建一个工作簿
wb = Workbook()
ws = wb.active

rows = [
    ['月份', '注册人数'],
    ['1月', 866],
    ['2月', 2335],
    ['3月', 5710],
    ['4月', 6482],
    ['5月', 6120],
    ['6月', 1605],
    ['7月', 3813],
    ['8月', 4428],
    ['9月', 4631],
]

for row in rows:
    ws.append(row)

#建立一个空的坐标系
c1 = LineChart() 

#向空坐标系中添加数据
data = Reference(ws, min_col=2, min_row=1, max_col=2, max_row=10)
c1.add_data(data, titles_from_data=True)#titles_from_data=True的作用是将表头不计入数据

#对图表元素进行设置
c1.title = "1-9月注册人数"
c1.style = 1 #图表样式类型(1-48)
c1.y_axis.title = '注册人数'
c1.x_axis.title = '月份'

#将图表添加到工作簿中
ws.add_chart(c1, "A8")

#将工作簿进行保存
wb.save(r'sample_chart.xlsx')

If there is a three-dimensional such as bubble chart


#建立一个空的坐标系
c1 = BubbleChart() 

#向空坐标系中添加数据
xvalues = Reference(ws, min_col=1, min_row=1, max_row=10)#x值
yvalues = Reference(ws, min_col=2, min_row=2, max_row=10)#y值
size = Reference(ws, min_col=3, min_row=1, max_row=10)#size值

series = Series(values=yvalues, xvalues=xvalues, zvalues=size)
c1.series.append(series)


#对图表元素进行设置
c1.title = "1-9月注册人数"
c1.style = 13 #图表样式类型(1-48)
c1.y_axis.title = '注册人数'
c1.x_axis.title = '月份'

#将图表添加到工作簿中
ws.add_chart(c1, "A8")

Guess you like

Origin blog.csdn.net/weixin_41867184/article/details/125557216