Python 非数值数据散点图
我正在学习使用matplotlib与熊猫,我有一点小麻烦。有一个数据框,其y和x标签分别为地区和咖啡馆。列值表示各个地区咖啡店的开始日期Python 非数值数据散点图,python,matplotlib,dataframe,Python,Matplotlib,Dataframe,我正在学习使用matplotlib与熊猫,我有一点小麻烦。有一个数据框,其y和x标签分别为地区和咖啡馆。列值表示各个地区咖啡店的开始日期 starbucks cafe-cool barista ........ 60 shops dist1 2008-09-18 2010-05-04 2007-02-21 ............... dist2 2007-06-12 2011-02-17 dist3
starbucks cafe-cool barista ........ 60 shops
dist1 2008-09-18 2010-05-04 2007-02-21 ...............
dist2 2007-06-12 2011-02-17
dist3
.
.
100 districts
我想画一个散点图,x轴作为时间序列,y轴作为咖啡馆。因为我无法找出一种直接的单线方式来绘制这个图,所以我将咖啡店提取为一个列表,将日期提取为另一个列表
shops = list(df.columns.values)
dt = pd.DataFrame(df.ix['dist1'])
dates = dt.set_index('dist1')
首先,我尝试了plt.plot(日期、商店)。得到一个ZeroDivisionError:整数除法或零误差模。我想不出原因。我在一些帖子上看到数据应该是数字的,所以我使用了ytick函数
y = [1, 2, 3, 4, 5, 6,...60]
仍然plt.plot(日期,y)
抛出了相同的错误。如果我能通过这个可能是我将能够使用滴答函数绘图。来源-
我正在尝试仅为第一行/距离1绘制图形。为此,我获取了第一行作为数据帧df1=df.ix[1]
,然后使用以下命令
for badges, dates in df.iteritems():
date = dates
ax.plot_date(date, yval)
# Record the number and label of the coffee shop
label_ticks.append(yval)
label_list.append(badges)
yval+=1
。
我在第
ax行得到一个错误。plot\u date(date,yval)
说x和y应该具有相同的第一维度。因为我正在为dist1的每个咖啡店一个接一个地绘图,所以x和y的长度不应该总是一个吗?PS:date是一个datetime.date对象要实现这一点,您需要将日期转换为datetime,有关详细信息,请参阅
举个例子。如前所述,您还需要将咖啡馆改造为
然后,一些编号系统会相应地更改记号标签
这里有一个尝试
import matplotlib.pyplot as plt
import matplotlib
import numpy as np
import pandas as pd
from datetime import datetime
def get_datetime(string):
"Converts string '2008-05-04' to datetime"
return datetime.strptime(string, "%Y-%m-%d")
# Generate datarame
df = pd.DataFrame(dict(
starbucks=["2008-09-18", "2007-06-12"],
cafe_cool=["2010-05-04", "2011-02-17"],
barista=["2007-02-21"]),
index=["dist1", "dist2"])
ax = plt.subplot(111)
label_list = []
label_ticks = []
yval = 1 # numbering system
# Iterate through coffee shops
for coffee_shop, dates in df.iteritems():
# Convert strings into datetime list
datetimes = [get_datetime(date) for date in dates]
# Create list of yvals [yval, yval, ...] to plot against
yval_list = np.zeros(len(dates))+yval
ax.plot_date(datetimes, yval_list)
# Record the number and label of the coffee shop
label_ticks.append(yval)
label_list.append(coffee_shop)
yval+=1 # Change the number so they don't all sit at the same y position
# Now set the yticks appropriately
ax.set_yticks(label_ticks)
ax.set_yticklabels(label_list)
# Set the limits so we can see everything
ax.set_ylim(ax.get_ylim()[0]-1,
ax.get_ylim()[1]+1)
日期“2008-09-18”是作为日期时间对象还是字符串传递的?在我看来,你应该遍历每个咖啡店,你能给出一个至少一个咖啡店的工作示例吗?你可以将x轴作为日期,y轴作为区域,然后使用第三个变量(用不同的颜色表示)勾勒出你60个不同的店。@Greg:日期作为字符串对象传递。你为一家咖啡店工作的例子是什么意思?一旦你确定了你的日期,还有一种很好的方法可以在答案中使用dicts将类别映射到数值,这就解决了我的问题。我仍然不明白为什么我会得到这个错误?我不能用你给的复制它。发布一个工作示例,给出错误,并且可能更容易诊断。