栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

python画散点图 - 坐标轴显示顺序与输入不一致解决

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

python画散点图 - 坐标轴显示顺序与输入不一致解决

问题描述:
散点图绘制,输入的x轴的值与图中的x轴的值顺序不同,默认会将输入的x轴的值先排序,再将xy对应画图,但实际期望按y的值排序画图。
解决:
用xticks修改x坐标值,需要注意,画散点图输入的x值先自定义,再替换。

代码:

import matplotlib.pyplot as plt

x_lst = ['10_abc', '9_ac', '12_ced', '12_cc', '20_de', '19_ab']
y_lst = [100, 80, 70, 50, 30, 10]

# 一开始绘图:发现和输入的x轴信息顺不一致(图1)
fig, ax = plt.subplots()
ax.scatter(x_lst, y_lst, alpha=0.5)
plt.xticks(rotation=90)
plt.show()

# 尝试调整x坐标显示:强行设定坐标,x轴的值和实际y轴不对应啦!!!(图2)
fig, ax = plt.subplots()
ax.scatter(x_lst, y_lst, alpha=0.5)
plt.xticks(range(len(x_lst)), x_lst, rotation=90)  # 不能强行设置,需要注意x和y的对应关系!
plt.show()

# 和预想的一致:(图3)
fig, ax = plt.subplots()
ax.scatter(range(len(x_lst)), y_lst, alpha=0.5)  # 先设定默认值
plt.xticks(range(len(x_lst)), x_lst, rotation=90)  # 再将默认值替换为xy对应的坐标值
plt.show()

图1:

图2:

图3:

import matplotlib.pyplot as plt
x_lst = ['10_abc', '9_ac', '12_ced', '12_cc', '20_de', 
         '19_ab', '5_d', '6_e', '8_s', 'abcd',
        ]
y_lst = [100, 80, 70, 50, 30, 
         10, 10, 8, 7, 6, 
         ]
# 加点颜色: (图4)
# C{i}: i取[0, 9), 只有10个值,超过则获取不到默认颜色
# https://matplotlib.org/2.0.2/users/colors.html
fig, ax = plt.subplots()
ax.scatter(range(len(x_lst)), y_lst, alpha=1, c=['C{}'.format(i) for i in range(len(x_lst))])  # 先设定默认值
plt.xticks(range(len(x_lst)), x_lst, rotation=90)  # 再将默认值替换为xy对应的坐标值
plt.show()

图4:

转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/757507.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号