【问题标题】:Matplotlib y axis values are not ordered [duplicate]Matplotlib y轴值未排序[重复]
【发布时间】:2018-06-12 05:59:13
【问题描述】:

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

这里是代码。

# -*- 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

【问题讨论】:

  • 哇,这真的很奇怪。不幸的是,我无法重现该行为,因为没有数据我无法运行您的代码。您能否提供一个重现该行为的minimal example
  • 这是因为你的数据是字符串
  • @DavidG 看了你的回答并立即捂脸
  • 我刚刚做了同样的事情 jmoz。

标签: python matplotlib plot


【解决方案1】:

发生这种情况的原因是因为您的数据被绘制为字符串

解决方案是将 y 轴数据转换为浮点数。这可以通过简单地转换为列表理解中的浮点数来完成:

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

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

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 轴随机排序我的数据集......果然我从 CSV 中提取数据,没有意识到我正在传递字符串。谢谢你结束了我的自我折磨。
  • 宾果游戏! The reason this happens is because your data is being plotted as strings.这句话挽救了一天。谢谢@DavidG
猜你喜欢
  • 2022-12-21
  • 2018-06-13
  • 2021-08-04
  • 1970-01-01
  • 2022-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多