Matplotlib y轴值未排序 [英] Matplotlib y axis values are not ordered

查看:158
本文介绍了Matplotlib y轴值未排序的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在尝试使用matplotlib进行绘图.该图显示了Y轴不排序的问题.

I am trying to plot using matplotlib. The plot showed a problem that the Y axis is not ordered.

这是代码.

# -*- coding: UTF-8 -*-
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
import datetime
import numpy as np
I020 = [ line.strip('\n').split(",") for line in 
open(r'D:\Users\a0476\Anaconda3\TickData\PV5sdata1.csv')][1:]
Time = [ datetime.datetime.strptime(line[0],"%H%M%S%f") for line in I020 ]
Time1 = [ mdates.date2num(line) for line in Time ]
Solar = [ line[1] for line in I020 ]
order = np.argsort(Time1)
xs = np.array(Time1)[order]
ys = np.array(Solar)[order]
plt.title('Solar data')
plt.xlabel('Time')
plt.ylabel('Solar')
ax.plot_date(xs, ys, 'k-')
hfmt = mdates.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_formatter(hfmt)
plt.show()

CSV数据

time        solar
7000000     50.35
8000000     41.01
9000000     69.16
10000000    94.5
11000000    111.9
12000000    103
13000000    98.6
14000000    36.45
15000000    34.74
16000000    34.17
17000000    34.6

推荐答案

发生这种情况的原因是因为您的数据被绘制为 strings .

The reason this happens is because your data is being plotted as strings.

解决方案是将y轴数据转换为浮点数.只需在列表理解中强制转换为浮点数即可完成

The solution is to convert your y axis data to floats. This can be done by simply casting to a float in your list comprehension:

Solar = [float(line[1]) for line in I020]

我还建议在使用日期/时间时使用matplotlib的x轴自动格式化.这将旋转标签等以使图形看起来更好:

I would also suggest to use matplotlib's auto formatting of the x -axis when using dates/times. This will rotate the labels etc to make the graph look better:

plt.gcf().autofmt_xdate()

您的示例变为:

I020 = [ line.strip('\n').split(",") for line in open('PV5sdata1.csv')][1:]
Time = [datetime.datetime.strptime(line[0],"%H%M%S%f") for line in I020]
Time1 = [mdates.date2num(line) for line in Time]
Solar = [float(line[1]) for line in I020]

xs = np.array(Time1)  # You don't really need to do this but I've left it in
ys = np.array(Solar)

fig, ax = plt.subplots() # using matplotlib's Object Oriented API

ax.set_title('Solar data')
ax.set_xlabel('Time')
ax.set_ylabel('Solar')
ax.plot_date(xs, ys, 'k-')

hfmt = mdates.DateFormatter('%H:%M:%S')
ax.xaxis.set_major_formatter(hfmt)
plt.gcf().autofmt_xdate()

plt.show()

哪个给:

这篇关于Matplotlib y轴值未排序的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆