增加在pandas Python中绘图的大小。

huangapple go评论79阅读模式
英文:

Increase the size of plots in pandas python

问题

Here's the translated portion of your text:

我希望创建一张折线图,根据年份和月份绘制min_days、avg_days、median_days和count的值。用于此目的的代码(运行良好)如下:

import matplotlib.pyplot as plt
result=freq_start_month_year_to_date_1(df,'Jan','2015','Dec','2019')

# 可视化

fig, ax = plt.subplots()
for col in ["Min_days", "Median_days", "Count",'Target_days_before_customer_dead']:
    ax.plot(result["Month Name-Year"], result[col], label=col)
ax.legend(loc="best")
ax.tick_params(axis="x", rotation=30)

我得到了一张图表。唯一的问题是,x轴太拥挤,所有值如2015-Jan、2015-Feb等重叠在一起,因此x轴上什么都看不清,看起来像是黑色涂鸦...我无法增加图表的大小。

我尝试了下面的代码,但也没有奏效:

fig, ax = plt.subplots(2,2, figsize=(20,20))

使用上面的代码,我得到了4个空子图。

Is there anything else you would like to know or need assistance with?

英文:

result

   year	 Month 	Min_days	Avg_days	Median_days	    Count MonthName-Year
    2015   1          9        12.56          10         4     2015-Jan
    2015   2          10       13.67          9          3     2015-Feb
   ........................................................
    2016   12       12       15.788           19          2    2016-Dec
    and so on...

I wish to create a line plot plotting min_days, avg_days, median_days, count according to month and year say. Code used for that(which works perfectly):

import matplotlib.pyplot as plt
result=freq_start_month_year_to_date_1(df,'Jan','2015','Dec','2019')

#Visualisations

fig, ax = plt.subplots()
for col in ["Min_days", "Median_days", "Count",'Target_days_before_customer_dead']:
    ax.plot(result["Month Name-Year"], result[col], label=col)
ax.legend(loc="best")
ax.tick_params(axis="x", rotation=30)

I am getting a plot . The only issue is that the x axis is too crowded and all the values 2015-Jan, 2015-Feb etc are overlapping so nothing is readable in the x axis, it looks like black scrabbling...I am unable to increase the size of the plot.

I tried below code but that too did not work

fig, ax = plt.subplots(2,2, figsize=(20,20))

Using the above code I got 4 empty sub plots

答案1

得分: 1

问题在于您将x轴预格式化为字符串,因此剥夺了matplotlib应用其自己的格式化程序的机会。matplotlib试图将所有字符串塞入轴中,因此您永远无法使其足够宽以容纳所有标签。

创建一个新的日期列并将其用于形成x轴:

from matplotlib import dates as mdates

# 用作x轴的新列
result['Date'] = pd.to_datetime(result[['Year', 'Month']].assign(Day=1))

# 绘制数据
fig, ax = plt.subplots(figsize=(10, 2))
for col in ['Min_days', 'Median_days', 'Count', 'Target_days_before_customer_dead']:
    ax.plot(result['Date'], result[col], label=col)

years = mdates.YearLocator()    # 仅打印年份标签
months = mdates.MonthLocator()  # 标记月份为刻度
years_fmt = mdates.DateFormatter('%Y')

ax.xaxis.set_major_locator(years)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_major_formatter(years_fmt)

ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

结果(带有随机数据):

增加在pandas Python中绘图的大小。

英文:

The problem is you preformatted your x-axis as string and thus robbed matplotlib of the chance to apply its own formatter. matplotlib tried to cram all the strings into the axis so you can never make it wide enough to hold all the labels.

Create a new date column and use it to form your x axis:

from matplotlib import dates as mdates

# The new column to be used as x axis
result['Date'] = pd.to_datetime(result[['Year', 'Month']].assign(Day=1))

# Plot the data
fig, ax = plt.subplots(figsize=(10, 2))
for col in ['Min_days', 'Median_days', 'Count', 'Target_days_before_customer_dead']:
    ax.plot(result['Date'], result[col], label=col)

years = mdates.YearLocator()    # only print label for the years
months = mdates.MonthLocator()  # mark months as ticks
years_fmt = mdates.DateFormatter('%Y')

ax.xaxis.set_major_locator(years)
ax.xaxis.set_minor_locator(months)
ax.xaxis.set_major_formatter(years_fmt)

ax.legend(loc='center left', bbox_to_anchor=(1, 0.5))

Result (with random data):

增加在pandas Python中绘图的大小。

huangapple
  • 本文由 发表于 2020年1月6日 22:23:34
  • 转载请务必保留本文链接:https://go.coder-hub.com/59613752.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定