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:
在这里插入图片描述

  • 3
    点赞
  • 7
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值