matplotlib数值按乱序绘制 [英] matplotlib numeric values are plotted out of order
本文介绍了matplotlib数值按乱序绘制的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我有一个数据文件,该数据文件包含多个y(y的+ ve和-ve值),对应于一个x值,如果我尝试使用matplotlib对其进行绘制,则会出现曲折线,我什至尝试了 np.sort
函数,但是并没有帮助.我附上 2 个数字,1 个是我需要的,2 个是我使用 matplotlib 得到的.任何评论/建议都会有很大帮助.
I have a data file that consist of multiple y (+ve and -ve values of y) values corresponding to a single x value, if I am trying to plot it using the matplotlib I am getting a zig-zag line, I even tried with the np.sort
function, but it hasn't helped. I am attaching 2 figures, the 1 one what I need and 2 one what I am getting using the matplotlib. Any comment/suggestion will be a great help.
import pandas as pd
import matplotlib.pyplot as plt
data = {0: [0.9991008043, 0.7186818868, 0.5990678817, 0.000260249999, -0.0002838699947, 0.9982619435, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.5990678817, 0.9987124801, 0.9983241558, 0.9979358315, 0.9975475073],
1: [0.141599882, -0.0239639965, -0.8235306015, -0.5624349256, 0.9576566094, 0.1070839175, -0.7615373918, -0.7436025052, -0.7207683284, -0.7181828611, -0.7169656166, -0.7189734963, -0.7248864019, -0.7334572909, -0.7431326927, -0.7535460886, -0.7653977208, -0.7772543193, -0.7850276183, -0.7882964598, -0.788996217, -0.7894645357, -0.7800111345, -0.7680467609, -0.7651210906, -0.7626205455, 0.1662477571, 0.1776703065, 0.178896989, 0.1792297328]}
df = pd.DataFrame(data)
0 1
0 0.999101 0.141600
1 0.718682 -0.023964
2 0.599068 -0.823531
plt.plot( df.iloc[:,0], df.iloc[:,1], marker="o", linewidth=2)
推荐答案
- 在这种情况下,数据被正确地转换为数字(例如
float
),但使用df 验证列
dtypes
通常是个好主意.info() - 需要使用
pandas.DataFrame.sort_values()
对 x 轴值进行排序- 我通常也会重置索引,但这并不是绝对必要的.
- In this case, the data is correctly cast as numeric (e.g.
float
), but it's usually a good idea to verify the columndtypes
withdf.info()
- It's required to sort the x-axis values with
pandas.DataFrame.sort_values()
- I typically also reset the index, but it's not strictly necessary.
# sort the values for the x-axis, which is column 0 df = df.sort_values(0).reset_index(drop=True) # plot the sorted data plt.plot(df.iloc[:,0], df.iloc[:,1], marker="o", linewidth=2)
- 也可以使用
pandas.DataFrame.plot
绘制数据
df.plot(x=0, y=1, marker='o', legend=False)
这篇关于matplotlib数值按乱序绘制的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文