簡體   English   中英

如何繪制帶有x和y分類軸的線圖?

[英]How to plot line graph with x and y categorical axis?

我正在嘗試繪制比較2個類別變量的折線圖。 但是我一直遇到錯誤。 我將代碼放在下面:

import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing", 
"washing"]

fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()

plt.show()

在此處提供答案:當使用matplotlib> = 2.1運行時,來自問題的代碼

import matplotlib.pyplot as plt

cat = ["bored", "happy", "bored", "bored", "happy", "bored"]
dog = ["happy", "happy", "happy", "happy", "bored", "bored"]
activity = ["combing", "drinking", "feeding", "napping", "playing", 
"washing"]

fig, ax = plt.subplots()
ax.plot(activity, dog, label="dog")
ax.plot(activity, cat, label="cat")
ax.legend()

plt.show()

運行良好並產生

在此處輸入圖片說明


對於較早版本的matplotlib,軸應為數字。 因此,您需要將類別轉換為數字,繪制它們,然后相應地設置刻度標簽。

 import numpy as np import matplotlib.pyplot as plt cat = ["bored", "happy", "bored", "bored", "happy", "bored"] dog = ["happy", "happy", "happy", "happy", "bored", "bored"] activity = ["combing", "drinking", "feeding", "napping", "playing", "washing"] catu, cati = np.unique(cat, return_inverse=True) dogu, dogi = np.unique(dog, return_inverse=True) fig, ax = plt.subplots() ax.plot(range(len(dog)), dogi, label="dog") ax.plot(range(len(cat)), cati, label="cat") ax.set_xticks(range(len(activity))) ax.set_xticklabels(activity) ax.set_yticks(range(len(catu))) ax.set_yticklabels(catu) ax.legend() plt.show() 

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM