I have this following code in order to generate scatterplots
import matplotlib.pyplot as plt
line = plt.figure()
plt.plot(xvalue, yvalue)
plt.grid(True)
plt.savefig("test.png")
plt.show()
and here is the screenshot of the plot:
I am just wondering if i could change the x-axis labels into strings. I have stored all the labels in
xlabel = ['2015/4/1', '2015/4/11', '2015/4/12', '2015/4/18', '2015/4/19'...]
Is there any function for matplotlib so that i could set x-axis labels to the values in "xlabel"?
many thx!
ALso my labels are overlapped, anything i could do to fix this problem? thx!
Here is my answer. You target was to plot the datetime as xticklabel.
I always do something like this. Code like this:
## For example, I have 9 daily value during 2013-04-01 to 2014-04-10
start = datetime.datetime.strptime("01-04-2013", "%d-%m-%Y")
end = datetime.datetime.strptime("10-04-2013", "%d-%m-%Y")
date = [start + datetime.timedelta(days=x) for x in range(0, (end-start).days)]
plt.figure(figsize=(12,4))
## y is the data I want to plot
ind = np.arange(len(y))
ax=plt.subplot()
plt.plot(ind,y,lw = 3)
k = []
for i in range(0,len(ind),1):
k.append(str(date[i])[0:10])
plt.xticks(ind,k,rotation=65)
Update
To solve the overlap problem, I recommend the code below:
for label in ax.xaxis.get_ticklabels()[::2]:
label.set_visible(False)
For daily value in a month, you can get a figure like this:
Do:
plt.xticks(xs, labels)
Where xs is a list of the positions for the ticks, and labels is the list of labels.
Related
i am making a plot on which the x axis represents dates and the y axis represents total covid cases. the problem is that due to a large dataset, there are many dates on the x axis and when i am ploting that i am getting a plot on which the xtick values are overlapped and i can not clearly see the covid cases at a particular date. so i want to make a clear graph. how can i do that? or you can also suggest me any better idea to make the graph more readable.
i am giving my code and plot below. Thanks.
ensure your dates are dates not strings
Use matplotlib date formatters
I've used data from UK as you did not provide sample
x = countries["date"]
y = countries["total_cases"]
fig, ax = plt.subplots(figsize=(10, 6))
locator = mdates.AutoDateLocator(minticks=3, maxticks=7)
formatter = mdates.ConciseDateFormatter(locator)
ax.xaxis.set_major_locator(locator)
ax.xaxis.set_major_formatter(formatter)
ax.plot(x, y)
I'm struggling to wrap my head around matplotlib with dataframes today. I see lots of solutions but I'm struggling to relate them to my needs. I think I may need to start over. Let's see what you think.
I have a dataframe (ephem) with 4 columns - Time, Date, Altitude & Azimuth.
I produce a scatter for alt & az using:
chart = plt.scatter(ephem.Azimuth, ephem.Altitude, marker='x', color='black', s=8)
What's the most efficient way to set the values in the Time column as the labels/ticks on the x axis?
So:
the scale/gridlines etc all remain the same
the chart still plots alt and az
the y axis ticks/labels remain as is
only the x axis ticks/labels are changed to the Time column.
Thanks
This isn't by any means the cleanest piece of code but the following works for me:
import matplotlib.pyplot as plt
fig, ax = plt.subplots()
ax.scatter(ephem.Azimuth, ephem.Altitude, marker='x', color='black', s=8)
labels = list(ephem.Time)
ax.set_xticklabels(labels)
plt.show()
Here you will explicitly force the set_xticklabels to the dataframe Time column which you have.
In other words, you want to change the x-axis tick labels using a list of values.
labels = ephem.Time.tolist()
# make your plot and before calling plt.show()
# insert the following two lines
ax = plt.gca()
ax.set_xticklabels(labels = labels)
plt.show()
I want to plot with data frames, but sometimes, I want more control over my x-tick labels and it looks like the data frame index is 'overruling' my code. here is the code:
test_df = pd.DataFrame({'cycles':[0,'b',3,'d','e','f','g'],'me':[100,80,99,100,75,100,90], 'you':[100,80,99,100,75,100,90], 'us':[100,80,99,100,75,100,90]})
f, ax = plt.subplots()
x = test_df['me']
x.index = ['a','b','c','d','e','f','g']
print(x)
for a in ax.get_xticklabels():
a.set_text('me')
print(ax.get_xticklabels()[0])
ax.plot(x)
test_df.plot(x = 'cycles', y = 'me')
any idea on easier ways to easily modify x-tick labels for data frames easily without changing the index of the data frame, but easily just on the fly making the x-ticks whatever I want for any data frame column I want?
You can specify the xticks within DataFrame.plot. This is basically just a dummy to ensure the number of tick labels is correct.
Then just set the tick labels manually after the plot.
import pandas as pd
import matplotlib.pyplot as plt
df = pd.DataFrame({'cycles':[0,'b',3,'d','e','f','g'],
'me':[100,80,99,100,75,100,90]})
fig, ax = plt.subplots()
test_df.plot(x='cycles', y='me', ax=ax, xticks=test_df.index)
_ = ax.set_xticklabels(test_df['cycles'])
plt.show()
But you should be a bit hesitant of how the xticks aren't automatically generated. Line plots make sense when your values are ordinal. It doesn't seem obvious to me that 0 should be connected with 'b' anymore than 'e' should be connected to 'f'. In this situation a bar plot makes sense, and not-surprisingly, the xticks are generated without issue.
test_df.plot(x='cycles', y='me', kind='bar', legend=False)
I'm trying to plot electricity usage against time. I'm using this script:
from datetime import datetime
import matplotlib.pyplot as plt
import numpy as np
timelist = []
valuelist = []
# Logic that populates timelist and valuelist
timeaxis = np.array(timelist)
valueaxis = np.array(valuelist)
plt.plot(timeaxis, valueaxis, 'r-')
plt.savefig('elec_use.png', bbox_inches='tight')
plt.show()
The x-axis labels in the plot I get running the program above is all crammed into the length of the graph.
I tried rotating the labels by adding xticks like so:
plt.xticks(timeaxis, rotation=90)
This causes the labels to get trimmed.
How can I fix the problem? I have tried adding plt.gcf().subplots_adjust(bottom=0.25) but this does not fix the labels, it merely increases the real estate to the bottom of the graph. I want the x-axis labels to say Jun 02 2016 or simply Jun 02. I don't mind the graph being wide. Thanks in advance for any help.
You could use gcf().autofmt_xdate to format the x-axis nicely. And for the date string format, you could use matplotlib.dates.DateFormatter. It will be something like below:
So you code will be something like this:
fig, ax = plt.subplots(1)
timelist = []
valuelist = []
# Logic that populates timelist and valuelist
timeaxis = np.array(timelist)
valueaxis = np.array(valuelist)
ax.plot(timeaxis, valueaxis, 'r-')
# rotate and align the tick labels so they look better
fig.autofmt_xdate()
# use a more precise date string for the x axis locations in the
# toolbar
import matplotlib.dates as mdates
ax.fmt_xdata = mdates.DateFormatter('%Y-%m-%d')
plt.savefig('elec_use.png', bbox_inches='tight')
plt.show()
I want to change x axis to years. The years are saves in the variable years.
I want to make plot of my data that looks like this:
It should look like this image
However, I am not able to create x axes with a years. My plot looks like the following image:
This is an example of produced image by my code
My code looks as follows:
import pandas as pd
import matplotlib.pyplot as plt
data = pd.read_csv("data1.csv")
demand = data["demand"]
years = data["year"]
plt.plot( demand, color='black')
plt.xlabel("Year")
plt.ylabel("Demand (GW)")
plt.show()
I am thankful for any advice.
The plot method in your example does not know the scaling of your data. So, for simplicity it treats the values of demand as being one unit apart from each other. If you want your x-axis to represent years, you have to tell matplotlib how many values of demand it should treat as "one year". If your data is a monthly demand, it is obviously 12 values per year. And here we go:
# setup a figure
fig, (ax1, ax2) = plt.subplots(2)
# generate some random data
data = np.random.rand(100)
# plot undesired way
ax1.plot(data)
# change the tick positions and labels ...
ax2.plot(data)
# ... to one label every 12th value
xticks = np.arange(0,100,12)
# ... start counting in the year 2000
xlabels = range(2000, 2000+len(xticks))
ax2.set_xticks(xticks)
ax2.set_xticklabels(xlabels)
plt.show()