首页 > 解决方案 > 如何在 matplotlib 中更新 y 轴

问题描述

我有问题更新限制y-axis。我的想法是阅读一些 csv 文件,并绘制一些图表。当我为 设置限制时y-axis,它不会显示在图上。它总是显示来自文件的值。

我是python新手。

import matplotlib.pyplot as plt
import csv
import numpy as np

x = []
y = []
chamber_temperature = []

with open(r"C:\Users\mm02058\Documents\test.txt", 'r') as file:
    reader = csv.reader(file, delimiter = '\t')

    for row in (reader):
        x.append(row[0])
        chamber_temperature.append(row[1])
        y.append(row[10])

x.pop(0)
y.pop(0)
chamber_temperature.pop(0)
#print(chamber_temperature)

arr = np.array(chamber_temperature)
n_lines = len(arr)
time = np.arange(0,n_lines,1)
time_sec = time * 30
time_min = time_sec / 60
time_hour = time_min / 60
time_day = time_hour / 24

Fig_1 = plt.figure(figsize=(10,8), dpi=100)
plt.suptitle("Powered Thermal Cycle", fontsize=14, x=0.56, y= 0.91)

plt.subplot(311, xlim=(0, 30), ylim=(-45,90), xticks=(0, 2, 4, 6, 8, 10, 12, 14, 16, 18, 20, 22, 24, 26, 28, 30), yticks=( -40, -30, -20, -10, 0, 10, 20, 30, 40, 50, 60, 70, 80, 90), ylabel=("Temperature [°C]"))
plt.plot(time_hour, chamber_temperature, 'k', label='Temperature')
plt.gca().invert_yaxis()
plt.grid()
plt.legend(shadow=True, fontsize=('small'), loc = 'center right', bbox_to_anchor=(1.13, 0.5))
plt.show()

在此处输入图像描述

标签: pythonmatplotlib

解决方案


您的代码看起来很可疑,因为我看不到从字符串(csv.reader产生的内容)到浮点数的转换。

此外,您的情节看起来很可疑,因为y刻度标签未排序!

我决定检查一下,Matplotlib 是否尝试变得比它应该的更聪明......

import numpy as np
import matplotlib.pyplot as plt

# let's plot an array of strings, as I suppose you did,
# and see if Matplotlib doesn't like it, or ...

np.random.seed(20210719)
arr_of_floats = 80+10*np.random.rand(10)
arr_of_strings = np.array(["x = %6.3f"%round(x, 2) for x in arr_of_floats])
plt.plot(range(10), arr_of_strings)
plt.show()

错误的情节

现在,让我们看看如果我们执行到浮点数的转换会发生什么

# for you it's simply: array(chamber_temperature, dtype=float)
arr_of_floats = np.array([s[4:] for s in arr_of_strings], dtype=float)
plt.plot(range(10), arr_of_floats)
plt.show()

正确的情节

最终,在绘图之前不要更改轴的限制(等),但是:

  • 首先,可能组织您的图形(图形大小、子图等)
  • 第二,绘制你的数据,
  • 第三,调整图表的细节和
  • 第四也是最后,使用plt.show().

推荐阅读