I'm trying to plot a graph with time data on X-Axis. My data has daily information, but I want to create something that has two different date scales on X-Axis.
I want to start it from 2005 and it goes to 2014, but after 2014, I want that, the data continues by months of 2015. Is this possible to do? If so: how can I create this kind of plot?
Thanks.
I provided an image below:
Yes you can, just use the following pattern as I observed your X-axis values are already the same so it would just plot the other graph on the right
For a dataframe:
import numpy, matplotlib
data = numpy.array([45,63,83,91,101])
df1 = pd.DataFrame(data, index=pd.date_range('2005-10-09', periods=5, freq='W'), columns=['events'])
df2 = pd.DataFrame(numpy.arange(10,21,2), index=pd.date_range('2015-01-09', periods=6, freq='M'), columns=['events'])
matplotlib.pyplot.plot(df1.index, df1.events)
matplotlib.pyplot.plot(df2.index, df2.events)
matplotlib.pyplot.show()
You can change the parameters according to your convenience.
Related
I have started using python for lots of data problems at work and the datasets are always slightly different. I'm trying to explore more efficient ways of plotting data using the inbuilt pandas function rather than individually writing out the code for each column and editing the formatting to get a nice result.
Background: I'm using Jupyter notebook and looking at histograms where the values are all unique integers.
Problem: I want the xtick labels to align with the centers of the histogram bars when plotting multiple columns of data with the one function e.g. df.hist() to get histograms of all columns at once.
Does anyone know if this is possible?
Or is it recommended to do each graph on its own vs. using the inbuilt function applied to all columns?
I can modify them individually following this post: Matplotlib xticks not lining up with histogram
which gives me what I would like but only for one graph and with some manual processing of the values.
Desired outcome example for one graph:
Basic example of data I have:
# Import libraries
import pandas as pd
import numpy as np
# create list of datapoints
data = [[170,30,210],
[170,50,200],
[180,50,210],
[165,35,180],
[170,30,190],
[170,70,190],
[170,50,190]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['height', 'width','weight'])
# print dataframe.
df
Code that displays the graphs in the problem statement
df.hist(figsize=(5,5))
plt.show()
Code that displays the graph for weight how I would like it to be for all
df.hist(column='weight',bins=[175,185,195,205,215])
plt.xticks([180,190,200,210])
plt.yticks([0,1,2,3,4,5])
plt.xlim([170, 220])
plt.show()
Any tips or help would be much appreciated!
Thanks
I hope this helps.You take the column and count the frequency of each label (value counts) then you specify sort_index in order to get the order by the label not by the frecuency, then you plot the bar plot.
data = [[170,30,210],
[170,50,200],
[180,50,210],
[165,35,180],
[170,30,190],
[170,70,190],
[170,50,190]]
# Create the pandas DataFrame
df = pd.DataFrame(data, columns = ['height', 'width','weight'])
df.weight.value_counts().sort_index().plot(kind = 'bar')
plt.show()
I am trying to plot this DataFrame which records various amounts of money over a yearly series:
from matplotlib.dates import date2num
jp = pd.DataFrame([1000,2000,2500,3000,3250,3750,4500], index=['2011','2012','2013','2014','2015','2016','2017'])
jp.index = pd.to_datetime(jp.index, format='%Y')
jp.columns = ['Money']
I would simply like to make a bar graph out of this using PyPlot (i.e pyplot.bar).
I tried:
plt.figure(figsize=(15,5))
xvals = date2num(jp.index.date)
yvals = jp['Money']
plt.bar(xvals, yvals, color='black')
ax = plt.gca()
ax.xaxis_date()
plt.show()
But the chart turns out like this:
Only by increasing the width substantially will I start seeing the bars. I have a feeling that this graph is attributing the data to the first date of the year (2011-01-01 for example), hence the massive space between each 'bar' and the thinness of the bars.
How can I plot this properly, knowing that this is a yearly series? Ideally the y-axis would contain only the years. Something tells me that I do not need to use date2num(), since this seems like a very common, ordinary plotting exercise.
My guess as to where I'm stuck is not handling the year correctly. As of now I have them as DateTimeIndex, but maybe there are other steps I need to take.
This has puzzled me for 2 days. All solutions I found online seems to use DataFrame.plot, but I would rather learn how to use PyPlot properly. I also intend to add two more sets of bars, and it seems like the most common way to do that is through plt.bar().
Thanks everyone.
You can either do
jp.plot.bar()
which gives:
or plot against the actual years:
plt.bar(jp.index.year, jp.Money)
which gives:
This question already has an answer here:
How to show timestamp x-axis in Python Plotly
(1 answer)
Closed 3 years ago.
I want to plot the data availability using pyplot. I got the code from #vestland. My monthly data is here.
In general, the data spans from January 2009 to January 2019. Each variable comes with its own time period.
Below is the code.
import pandas as pd
import plotly.express as px
path = r'C:\Users\....\availability3.txt'
df = pd.read_csv(path)
df = df.drop(['Unnamed: 0'], axis=1)
fig = px.bar(df, x="Timestamp", y="variable", color='value', orientation='h',
hover_data=["Timestamp"],
height=300,
color_continuous_scale=['firebrick', '#2ca02c'],
title='Data Availabiltiy Plot',
template='plotly_white',
)
fig.update_layout(yaxis=dict(title=''),
xaxis=dict(
title='',
showgrid=True,
gridcolor='white',
tickvals=[]
)
)
fig.show()
As you can see below, the plot shows only the first row of the data which is the first day.
What I want is to show the whole range of the data on the x axis with corresponding values and colors. The result should show data from January 2009 to January 2019, variable values of 0 is shown on red and 1 in green.
Perhaps this is an issue with timestamp, because when using the number index, the plot is just okay.
Edit
By removing duplicates in the dataset and set timestamp as index, I got an almost the expected result. This the new code.
fig = px.bar(df, y="variable", color='value', orientation='h',
hover_data=[df.index],
height=300,
color_continuous_scale=['firebrick', '#2ca02c'],
title='Data Availabiltiy Plot',
template='plotly_white',
)
Now the whole time span is showing as expected. But the value of x-axis timestamp is not yet showing. I will ask in another post
I checked the documentation for plotly.express.bar and briefly worked with your code. Your data may be stacked one on top of each other.
Setting orientation='v' shows all of the data, but not in any particularly intuitive way, although I believe it does answer the question you asked. Yes, the data for Alice, Thalia, Citra, and Pebaru are all present, but the y-axis needs modification to get the proper labels:
Alternatively, setting orientation='h' and barmode='overlay' shows all of the data when you hover, but not as individual bars. You can see the overlay blur on the right edge of the bars:
There are quite a few arguments for plotly.express.bar in the documentation: https://plot.ly/python-api-reference/generated/plotly.express.bar.html#plotly.express.bar. Experiment around and see what you can come up with.
EDIT:
1) Set the x-axis independently using the Timeframe column.
2) Use .groupby() with an averaging function on value.
I'm trying to plot a histogram of dates from a pandas dataframe. I have had a look at this question Can Pandas plot a histogram of dates? and some others, and while this works it is plotting a bar chart instead of a histogram.
Is there an easy way of plotting a histogram of dates or should I extract the year as numbers and plot a histogram of an array of numbers?
Thanks!
You can explicitly register a converter using:
pd.plotting.register_matplotlib_converters()
By default you can't plot dates using the plotting functionality in pandas so you must explicitly register a converter like this.
As a very simple example try:
pd.plotting.register_matplotlib_converters()
df = pd.DataFrame({'date': [pd.to_datetime('1/1/2019')]*8 + [pd.to_datetime('2/1/2019')]*4})
df['date'].hist()
which will return:
I would like to create a Holoviews bar chart (using Bokeh backend) in which Year is on the X-axis and columns A and B on the Y-Axis. For each Year, I want bars for values from columns A and B to appear next to each other i.e. for Year 2008, I have bars of heights 1 and 3, for year 2009, I have bars 3 and 6 height, and so on. I have tried numerous different ways including the example of grouped bars in the documentation but can't get it to work. See example below:
%%opts Bars [xrotation=90 width=600 show_legend=False tools=['hover']]
df=pd.DataFrame({'Year':[2008,2009,2010,2011,2012,2013],
'A': [1,2,3,4,5,6],'B':[3,6,9,12,15,18]})
print(df)
bars = hv.Bars(df, kdims=['Year'], vdims=['A'])
bars
Please help. I am losing my mind!
HoloViews generally works best when your data is in what's called a tidy format. However to make it easier to work with data like yours we have developed a companion library called hvPlot. To generate the plot you want you can simply run:
import hvplot.pandas
df=pd.DataFrame({'Year':[2008,2009,2010,2011,2012,2013],
'A': [1,2,3,4,5,6],'B':[3,6,9,12,15,18]})
df.hvplot.bar('Year')
Alternatively you can learn about the pd.melt method, which can take your data in a wide format and convert it to a tidy dataset:
%%opts Bars [xrotation=90 width=600 show_legend=False tools=['hover']]
df=pd.DataFrame({'Year':[2008,2009,2010,2011,2012,2013],
'A': [1,2,3,4,5,6],'B':[3,6,9,12,15,18]})
tidy_df = df.melt(id_vars=['Year'], value_vars=['A', 'B'])
bars = hv.Bars(tidy_df, ['Year', 'variable'], ['value'])
bars
To respond to #pongo30 you can suppress printing 'A' and 'B' on the x-axis by adding .opts(xlabel='') to the call to hvplot.bar() (ex: df.hvplot.bar('Year').opts(xlabel=''))