使用 matplotlib 繪製資料折線圖 #4
-
以簡單的日期-收盤價資料為例 import matplotlib.pyplot as plt
datas = [{'date': '113/01/02', 'close_price': '34.00', 'total_count': '1,071'},
{'date': '113/01/03', 'close_price': '34.30', 'total_count': '1,160'},
{'date': '113/01/04', 'close_price': '34.60', 'total_count': '3,671'},
{'date': '113/01/05', 'close_price': '34.30', 'total_count': '1,393'},
{'date': '113/01/08', 'close_price': '33.80', 'total_count': '738'},
{'date': '113/01/09', 'close_price': '33.10', 'total_count': '1,073'},
{'date': '113/01/10', 'close_price': '32.55', 'total_count': '1,074'},
{'date': '113/01/11', 'close_price': '33.40', 'total_count': '779'},
{'date': '113/01/12', 'close_price': '32.95', 'total_count': '760'},
{'date': '113/01/15', 'close_price': '33.70', 'total_count': '584'},
{'date': '113/01/16', 'close_price': '33.35', 'total_count': '825'},
{'date': '113/01/17', 'close_price': '32.60', 'total_count': '1,014'},
{'date': '113/01/18', 'close_price': '32.05', 'total_count': '726'},
{'date': '113/01/19', 'close_price': '32.35', 'total_count': '496'}
]
# The data for x- and y-axis
dates_str = [d['date'] for d in datas]
close_prices = [float(d['close_price']) for d in datas]
# Create the plot by assigning the size; assigning the x-axis, y-axis, and marker
plt.figure(figsize=(10, 5))
plt.plot(dates_str, close_prices, marker='o')
# Adding labels and title
plt.xlabel('Date')
plt.ylabel('Close Price')
plt.title('Close Price vs Date')
plt.grid(True)
# Adding data labels
for i in range(len(dates_str)):
plt.text(dates_str[i], close_prices[i], f"{close_prices[i]}")
# Rotate date labels for better readability
plt.xticks(rotation=45)
plt.show() |
Beta Was this translation helpful? Give feedback.
Answered by
philosopher1121
Jan 21, 2024
Replies: 1 comment
-
謝謝老師,我大概知道是我在y的取值的地方,沒有轉換成數字所以還是文字,所以才會產生之前無法按照大小排序的問題,所以加上float()之後就順利畫出來了,感激老師的指導!!! |
Beta Was this translation helpful? Give feedback.
0 replies
Answer selected by
jwlin
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
謝謝老師,我大概知道是我在y的取值的地方,沒有轉換成數字所以還是文字,所以才會產生之前無法按照大小排序的問題,所以加上float()之後就順利畫出來了,感激老師的指導!!!