search
HomeBackend DevelopmentPython TutorialPython-matplotlib | Draw dual y-axis graphics (legend settings)


Today I will introduce to you how to use Python’s matplotlib library to draw a double y-axis graph And the legend setting problem , I hope it will be helpful to everyone. If you have any questions or suggestions, you can send a private message to the editor.
Rendering preview:

Python-matplotlib | Draw dual y-axis graphics (legend settings)

Sample data:
##
df = pd.read_csv('jobdata.csv')
Python-matplotlib | Draw dual y-axis graphics (legend settings)

# 1. Double y-axis line chart

##1 . Position number line chart

##
colors = ["#51C1C8", "#536D84","#E96279"]
plt.figure(figsize=(16, 8))
ax1 = plt.subplot(111)
ax1.set_ylim(0,1200)
lin0 = ax1.plot(x_data, y_data1, marker='o', color=colors[0], label='岗位数量') 
for x, y in enumerate(y_data1):
    plt.text(x - 0.2, y+5, y)
ax1.set_ylabel('岗位数量',fontsize=12)
plt.legend()
plt.title("各城市Java岗位数量")
plt.show()
##2. Add a y-axis through ax1.twinx():

Python-matplotlib | Draw dual y-axis graphics (legend settings)

# 增加y轴
ax2 = ax1.twinx()

ax2.set_ylim(0,60)
lin1 = ax2.plot(x_data, y_data2, linestyle='--', marker='o', c=colors[1], label='平均最低薪资') 
for x, y in enumerate(y_data2):
    plt.text(x - 0.1, y+1, y)
lin2 = ax2.plot(x_data, y_data3, linestyle='--', marker='o', c=colors[2], label='平均最高薪资')
for x, y in enumerate(y_data3):
    plt.text(x - 0.1, y+1, y)
ax2.set_ylabel('平均薪资(万/年)',fontsize=12)
plt.legend()
plt.title("各城市Java岗位数量和薪资水平状况")
plt.show()

重点:细心的小伙伴可能发现了图没有问题,但是右上角的图例只显示了平均最低薪资和平均最薪资,但是岗位数量的图例并没有显示。

3. 单独设置图例

ax1.legend(loc='best')
ax2.legend(loc='best')

Python-matplotlib | Draw dual y-axis graphics (legend settings)

看着感觉没什么变化,实际上仔细看会发现平均最低薪资、平均最高薪资、岗位数量三个图例都显示出来了,只不过岗位数量图例被盖住了,我们可以移动一下位置看看:
ax1.legend(loc=2)
ax2.legend(loc=1)

Python-matplotlib | Draw dual y-axis graphics (legend settings)

这样看就比较直观了,但是我就想把三个图例放一起不可以吗?

当然可以!

3. 设置组合图例

lines = lin0+lin1+lin2
labs = [label.get_label() for label in lines]
plt.legend(lines,labs)

Python-matplotlib | Draw dual y-axis graphics (legend settings)


大功告成!

但是!如果是柱状图+折线图的情况,效果还一样吗?

但是!如果是柱状图+折线图的情况,效果还一样吗?

但是!如果是柱状图+折线图的情况,效果还一样吗?


2、双y轴柱状图+折线图

1. 修改岗位数量为柱状图

plt.figure(figsize=(16, 8))
a1 = plt.subplot(111)
a1.set_ylim(0,1200)
bar = a1.bar(x_data, y_data1, color=colors[0], label='岗位数量') 
for x, y in enumerate(y_data1):
    plt.text(x - 0.2, y+5, y)
a1.set_ylabel('岗位数量',fontsize=12)

...

lines = bar+lin1+lin2
labs = [label.get_label() for label in lines]
plt.legend(lines,labs)

直接报错了!Python-matplotlib | Draw dual y-axis graphics (legend settings)Python-matplotlib | Draw dual y-axis graphics (legend settings)Python-matplotlib | Draw dual y-axis graphics (legend settings)

Python-matplotlib | Draw dual y-axis graphics (legend settings)

The prompt type is inconsistent. It is obviously a problem with the type of bar and line. Let’s check the source code:

matplotlib.axes.Axes.plot:

Python-matplotlib | Draw dual y-axis graphics (legend settings)

matplotlib.axes.Axes.bar:

Python-matplotlib | Draw dual y-axis graphics (legend settings)

ax.plot returns a Line2D type list, ax.bar returns a patches Type tuple.
#After finding the root cause, we can just make a combination of line2D and patches.

2. 设置Line2D和patches的组合图例

legend_handles = [ 
    Line2D([], [], linewidth=1, ls='--', lw=2, c=colors[2], label='平均最高薪资'),
    Line2D([], [], linewidth=1, lw=2, c=colors[1], label='平均最低薪资'),
    patches.Rectangle((0, 0), 1, 1, facecolor=colors[0],label='岗位数量')
]
plt.legend(handles=legend_handles, loc='best', fontsize=14)
效果:
Python-matplotlib | Draw dual y-axis graphics (legend settings)
其他参数大家可以自行尝试修改,对比前后效果,加深理解。

The above is the detailed content of Python-matplotlib | Draw dual y-axis graphics (legend settings). For more information, please follow other related articles on the PHP Chinese website!

Statement
This article is reproduced at:Python当打之年. If there is any infringement, please contact admin@php.cn delete
详细讲解Python之Seaborn(数据可视化)详细讲解Python之Seaborn(数据可视化)Apr 21, 2022 pm 06:08 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于Seaborn的相关问题,包括了数据可视化处理的散点图、折线图、条形图等等内容,下面一起来看一下,希望对大家有帮助。

详细了解Python进程池与进程锁详细了解Python进程池与进程锁May 10, 2022 pm 06:11 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于进程池与进程锁的相关问题,包括进程池的创建模块,进程池函数等等内容,下面一起来看一下,希望对大家有帮助。

Python自动化实践之筛选简历Python自动化实践之筛选简历Jun 07, 2022 pm 06:59 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于简历筛选的相关问题,包括了定义 ReadDoc 类用以读取 word 文件以及定义 search_word 函数用以筛选的相关内容,下面一起来看一下,希望对大家有帮助。

归纳总结Python标准库归纳总结Python标准库May 03, 2022 am 09:00 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于标准库总结的相关问题,下面一起来看一下,希望对大家有帮助。

Python数据类型详解之字符串、数字Python数据类型详解之字符串、数字Apr 27, 2022 pm 07:27 PM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于数据类型之字符串、数字的相关问题,下面一起来看一下,希望对大家有帮助。

分享10款高效的VSCode插件,总有一款能够惊艳到你!!分享10款高效的VSCode插件,总有一款能够惊艳到你!!Mar 09, 2021 am 10:15 AM

VS Code的确是一款非常热门、有强大用户基础的一款开发工具。本文给大家介绍一下10款高效、好用的插件,能够让原本单薄的VS Code如虎添翼,开发效率顿时提升到一个新的阶段。

详细介绍python的numpy模块详细介绍python的numpy模块May 19, 2022 am 11:43 AM

本篇文章给大家带来了关于Python的相关知识,其中主要介绍了关于numpy模块的相关问题,Numpy是Numerical Python extensions的缩写,字面意思是Python数值计算扩展,下面一起来看一下,希望对大家有帮助。

python中文是什么意思python中文是什么意思Jun 24, 2019 pm 02:22 PM

pythn的中文意思是巨蟒、蟒蛇。1989年圣诞节期间,Guido van Rossum在家闲的没事干,为了跟朋友庆祝圣诞节,决定发明一种全新的脚本语言。他很喜欢一个肥皂剧叫Monty Python,所以便把这门语言叫做python。

See all articles

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
2 weeks agoBy尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks agoBy尊渡假赌尊渡假赌尊渡假赌

Hot Tools

SAP NetWeaver Server Adapter for Eclipse

SAP NetWeaver Server Adapter for Eclipse

Integrate Eclipse with SAP NetWeaver application server.

Dreamweaver Mac version

Dreamweaver Mac version

Visual web development tools

SecLists

SecLists

SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.

SublimeText3 Linux new version

SublimeText3 Linux new version

SublimeText3 Linux latest version

EditPlus Chinese cracked version

EditPlus Chinese cracked version

Small size, syntax highlighting, does not support code prompt function