首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >matplotlib:如何防止x轴标签重叠

matplotlib:如何防止x轴标签重叠
EN

Stack Overflow用户
提问于 2012-11-22 23:05:58
回答 4查看 100.7K关注 0票数 53

我正在用matplotlib生成一个条形图。这一切都很好用,但我想不出如何防止x轴的标签相互重叠。下面是一个示例:

以下是postgres 9.1数据库的一些示例SQL:

代码语言:javascript
复制
drop table if exists mytable;
create table mytable(id bigint, version smallint, date_from timestamp without time zone);
insert into mytable(id, version, date_from) values

('4084036', '1', '2006-12-22 22:46:35'),
('4084938', '1', '2006-12-23 16:19:13'),
('4084938', '2', '2006-12-23 16:20:23'),
('4084939', '1', '2006-12-23 16:29:14'),
('4084954', '1', '2006-12-23 16:28:28'),
('4250653', '1', '2007-02-12 21:58:53'),
('4250657', '1', '2007-03-12 21:58:53')
;  

这是我的python脚本:

代码语言:javascript
复制
# -*- coding: utf-8 -*-
#!/usr/bin/python2.7
import psycopg2
import matplotlib.pyplot as plt
fig = plt.figure()

# for savefig()
import pylab

###
### Connect to database with psycopg2
###

try:
  conn_string="dbname='x' user='y' host='z' password='pw'"
  print "Connecting to database\n->%s" % (conn_string)

  conn = psycopg2.connect(conn_string)
  print "Connection to database was established succesfully"
except:
  print "Connection to database failed"

###
### Execute SQL query
###  

# New cursor method for sql
cur = conn.cursor()

# Execute SQL query. For more than one row use three '"'
try:
  cur.execute(""" 

-- In which year/month have these points been created?
-- Need 'yyyymm' because I only need Months with years (values are summeed up). Without, query returns every day the db has an entry.

SELECT to_char(s.day,'yyyymm') AS month
      ,count(t.id)::int AS count
FROM  (
   SELECT generate_series(min(date_from)::date
                         ,max(date_from)::date
                         ,interval '1 day'
          )::date AS day
   FROM   mytable t
   ) s
LEFT   JOIN mytable t ON t.date_from::date = s.day
GROUP  BY month
ORDER  BY month;

  """)

# Return the results of the query. Fetchall() =  all rows, fetchone() = first row
  records = cur.fetchall()
  cur.close()

except:
  print "Query could not be executed"

# Unzip the data from the db-query. Order is the same as db-query output
year, count = zip(*records)

###
### Plot (Barchart)
###

# Count the length of the range of the count-values, y-axis-values, position of axis-labels, legend-label
plt.bar(range(len(count)), count, align='center', label='Amount of created/edited points')

# Add database-values to the plot with an offset of 10px/10px
ax = fig.add_subplot(111)
for i,j in zip(year,count):
    ax.annotate(str(j), xy=(i,j), xytext=(10,10), textcoords='offset points')

# Rotate x-labels on the x-axis
fig.autofmt_xdate()

# Label-values for x and y axis
plt.xticks(range(len(count)), (year))

# Label x and y axis
plt.xlabel('Year')
plt.ylabel('Amount of created/edited points')

# Locate legend on the plot (http://matplotlib.org/users/legend_guide.html#legend-location)
plt.legend(loc=1)

# Plot-title
plt.title("Amount of created/edited points over time")

# show plot
pylab.show()

有没有办法防止标签相互重叠?理想情况下是自动的,因为我无法预测条形图的数量。

EN

回答 4

Stack Overflow用户

回答已采纳

发布于 2012-11-24 03:37:18

  • 操作中的问题是日期被格式化为string类型。matplotlib将每个值绘制为刻度标签,刻度位置是基于值数的0索引数字。
  • 解决此问题的方法是将所有值转换为正确的type,在本例中为datetime
    • 一旦axes有了正确的type,就会有额外的matplotlib methods可用于进一步自定义tick spacing.

原始答案

下面是如何将日期字符串转换为实时datetime对象:

代码语言:javascript
复制
import numpy as np
import matplotlib.pyplot as plt
import matplotlib.dates as mdates
data_tuples = [
    ('4084036', '1', '2006-12-22 22:46:35'),
    ('4084938', '1', '2006-12-23 16:19:13'),
    ('4084938', '2', '2006-12-23 16:20:23'),
    ('4084939', '1', '2006-12-23 16:29:14'),
    ('4084954', '1', '2006-12-23 16:28:28'),
    ('4250653', '1', '2007-02-12 21:58:53'),
    ('4250657', '1', '2007-03-12 21:58:53')]
datatypes = [('col1', 'i4'), ('col2', 'i4'), ('date', 'S20')]
data = np.array(data_tuples, dtype=datatypes)
col1 = data['col1']

# convert the dates to a datetime type
dates = mdates.num2date(mdates.datestr2num(data['date']))
fig, ax1 = plt.subplots()
ax1.bar(dates, col1)
fig.autofmt_xdate()

从数据库游标中获取一个简单的元组列表应该很简单,如下所示:

代码语言:javascript
复制
data_tuples = []
for row in cursor:
    data_tuples.append(row)

然而,我在这里发布了一个函数的版本,我使用该函数将db游标直接用于记录数组或熊猫数据帧:How to convert SQL Query result to PANDAS Data Structure?

希望这也能有所帮助。

票数 14
EN

Stack Overflow用户

发布于 2012-11-23 08:10:30

我认为您对matplotlib如何处理日期的几点感到困惑。

目前,您实际上并不是在绘制日期。使用[0,1,2,...]在x轴上绘制图形,然后用日期的字符串表示手动标记每个点。

Matplotlib将自动定位刻度。然而,您覆盖了matplotlib的tick定位功能(使用xticks基本上就是在说:“我希望ticks正好位于这些位置”)。

目前,如果[10, 20, 30, ...]库自动定位它们,您将在matplotlib处获得它们。但是,这些值将对应于您用来绘制它们的值,而不是日期(您在绘制时没有使用)。

您可能希望实际使用日期来绘制内容。

目前,您正在做这样的事情:

代码语言:javascript
复制
import datetime as dt
import matplotlib.dates as mdates
import numpy as np
import matplotlib.pyplot as plt

# Generate a series of dates (these are in matplotlib's internal date format)
dates = mdates.drange(dt.datetime(2010, 01, 01), dt.datetime(2012,11,01), 
                      dt.timedelta(weeks=3))

# Create some data for the y-axis
counts = np.sin(np.linspace(0, np.pi, dates.size))

# Set up the axes and figure
fig, ax = plt.subplots()

# Make a bar plot, ignoring the date values
ax.bar(np.arange(counts.size), counts, align='center', width=1.0)

# Force matplotlib to place a tick at every bar and label them with the date
datelabels = mdates.num2date(dates) # Go back to a sequence of datetimes...
ax.set(xticks=np.arange(dates.size), xticklabels=datelabels) #Same as plt.xticks

# Make space for and rotate the x-axis tick labels
fig.autofmt_xdate()

plt.show()

取而代之的是,尝试这样做:

代码语言:javascript
复制
import datetime as dt
import matplotlib.dates as mdates
import numpy as np
import matplotlib.pyplot as plt

# Generate a series of dates (these are in matplotlib's internal date format)
dates = mdates.drange(dt.datetime(2010, 01, 01), dt.datetime(2012,11,01), 
                      dt.timedelta(weeks=3))

# Create some data for the y-axis
counts = np.sin(np.linspace(0, np.pi, dates.size))

# Set up the axes and figure
fig, ax = plt.subplots()

# By default, the bars will have a width of 0.8 (days, in this case) We want
# them quite a bit wider, so we'll make them them the minimum spacing between
# the dates. (To use the exact code below, you'll need to convert your sequence
# of datetimes into matplotlib's float-based date format.  
# Use "dates = mdates.date2num(dates)" to convert them.)
width = np.diff(dates).min()

# Make a bar plot. Note that I'm using "dates" directly instead of plotting
# "counts" against x-values of [0,1,2...]
ax.bar(dates, counts, align='center', width=width)

# Tell matplotlib to interpret the x-axis values as dates
ax.xaxis_date()

# Make space for and rotate the x-axis tick labels
fig.autofmt_xdate()

plt.show()

票数 37
EN

Stack Overflow用户

发布于 2013-01-21 17:55:18

至于你关于如何在X轴上只显示每四个刻度(例如)的问题,你可以这样做:

代码语言:javascript
复制
import matplotlib.ticker as mticker

myLocator = mticker.MultipleLocator(4)
ax.xaxis.set_major_locator(myLocator)
票数 17
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/13515471

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档