未显示python matploblib图形

2024-09-30 04:30:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我是python新手,我不知道为什么我的条形图没有显示任何东西。任何帮助都将不胜感激! 使用的数据集:https://data.gov.sg/dataset/public-transport-utilisation-average-trip-distance

import numpy as np
import matplotlib.pyplot as plt

ptrip = np.genfromtxt("data/public-transport-utilisation-average-trip-distance.csv",
                      dtype=(int,"U100",float),
                      delimiter=",",
                      names=True)

years = np.unique(ptrip["year"])

modes = np.unique(ptrip["mode"])

distances = ptrip["ave_distance_per_trip"]

avgs = []
labels = []
for c in distances:
    labels.append(c)
    mu = np.mean(ptrip[ptrip["mode"]==c]["ave_distance_per_trip"])
    avgs.append(mu)


plt.figure(figsize=(7, 6))
bar0 = plt.bar(labels,avgs,color="blue")
plt.xlabel("public transport")
plt.xticks(rotation='vertical')
plt.ylabel("Average distance per trip")
plt.show()

Tags: importdatalabelsasnppltpublicdistance
1条回答
网友
1楼 · 发布于 2024-09-30 04:30:53

mu的计算看起来是错误的,因为ptrip["mode"]==c总是返回false,因为您将“mode”中的字符串与浮点距离c进行比较。因此,avgs数组只是一堆nan值。matplotlib反过来会将其解释为“无”,因此您不会绘制任何内容

编辑:尽管有很多东西可以从这个数据集中绘制出来,但我能找到的最简单的错误是,您在distance而不是模式中循环。因此,一个地块的工作代码(多年来每种运输方式每次出行的平均距离)为:

import numpy as np
import matplotlib.pyplot as plt

ptrip = np.genfromtxt("/home/christopher/test/public-transport-utilisation-average-trip-distance.csv",
                      dtype=(int,"U100",float),
                      delimiter=",",
                      names=True)

years = np.unique(ptrip["year"])

modes = np.unique(ptrip["mode"])

distances = ptrip["ave_distance_per_trip"]

avgs = []
labels = []
for c in modes: # Note the change from distances to modes here
    labels.append(c)
    mu = np.mean(ptrip[ptrip["mode"]==c]["ave_distance_per_trip"])
    avgs.append(mu)


plt.figure(figsize=(7, 6))
bar0 = plt.bar(labels,avgs,color="blue")
plt.xlabel("public transport")
plt.xticks(rotation='vertical')
plt.ylabel("Average distance per trip")
plt.show()

相关问题 更多 >

    热门问题