Skip to main content
 首页 » 编程设计

python之pyplot 轴和图之间的距离

2024年11月01日10pengyingh

我正在尝试制作图表来显示数据库中的日常数据。我在这里为特定的一天制作了这张图表。我对这里的一些细节不太满意,我不知道应该寻找什么关键字。

我有的是

但我希望图表看起来像(忽略颜色等):

在我的图像中,x 轴上的时间从创建第一个时间戳时开始(在图像显示的那天是上午 8 点,但每天都从不同的时间开始),但我希望时间总是从 7:00:00 开始.这是 TimeStamp 最早创建的时间。

其次,我想在图的边缘和第一个/最后一个条之间留出一些空间。我不希望条形图触及情节的边缘。

我的代码在这里。

import MySQLdb 
import numpy as np 
import matplotlib 
matplotlib.use('Agg') 
import matplotlib.pyplot as plt 
import pandas as pd 
 
# connect to MySQL database 
conn = MySQLdb.connect(host="localhost", user="r1", passwd="!r1db!", 
db="r1array") 
# prepare a cursor 
cur = conn.cursor() 
 
# this is the query we'll be making 
query = """SELECT TimeStamp,Pac FROM SolarData WHERE DATE(`TimeStamp`) = CURDATE()-6 GROUP BY HOUR(TimeStamp);""" 
 
# execute the query 
cur.execute(query) 
# retrieve the whole result set 
data = cur.fetchall() 
 
# close cursor and connection 
cur.close() 
conn.close() 
 
# unpack data in TimeStamp (x axis) and Pac (y axis) 
TimeStamp, Pac = zip(*data) 
 
# graph code 
fig = plt.figure() 
ax = fig.add_subplot() 
plt.bar(TimeStamp, Pac, align='center', width=0.015) 
 
# set title, X/Y labels 
plt.title("PVIC R1 panel ") 
plt.xlabel("Hour") 
plt.ylabel("Pac") 
fig = plt.gcf() 
fig.set_size_inches(20.5,10.5) 
plt.grid(True) 
plt.draw() 
fig.savefig('test.png', dpi=100) 

请您参考如下方法:

... I want the hours always start from 7:00:00 ... Second, I want to make some spaces between the edge of the plot and the first/last bar.

使用plt.xlim设置开始和结束时间。这是一些玩具数据的示例:

import datetime 
import pylab as plt 
 
# Some sample data 
X = [datetime.datetime(2000, 3, 2, n) for n in xrange(9,13)] 
Y = [4,8,3,2] 
 
# Set the limits 
start_time = datetime.datetime(2000, 3, 2, 7) 
end_time = datetime.datetime(2000, 3, 2, 14) 
 
plt.bar(X, Y, align='center',width=.015) 
plt.gcf().autofmt_xdate() 
plt.xlim(start_time, end_time) 
plt.show()