plotting a model based on data - numpy

I want to plot a velocity versus depth model using the given data.
import matplotlib.pyplot as plt
import numpy as np
depth=np.array((0.0,5.0,30.0,40.0,50.0))
velocity=np.array((5.5,6.5,6.8,9.0,10.0))
plt.plot(velocity,depth)
plt.show()
But this script doesnot give the plot as i expected
I need something like example_plot
I hope experts may help me overcoming this problem. Thanks in advance.

You have to use matplotlib.pyplot.step
depth=np.array((0.0,5.0,30.0,40.0,50.0))*-1
velocity=np.array((5.5,6.5,6.8,9.0,10.0))
plt.step(velocity,depth)
plt.show()
EDIT:
depth=np.array((0.0,5.0,30.0,40.0,50.0))
velocity=np.array((5.5,6.5,6.8,9.0,10.0))
fig, ax = plt.subplots()
ax.step(velocity,depth)
ax.invert_yaxis()
fig.show()

Related

How do I plot two graphs of two different dataframes side by side?

I have two DataFrames that have time-series data of BTC. I want to display the graphs side by side to analyze them.
display(data_df.plot(figsize=(15,20)))
display(model_df.plot(figsize=(15,20)))
When I plot them like this they stack on top of each-other vertically. I want them side-by-side so they look like this.
enter image description here
Heres one way that might work using subplots (Im guessing you want a total figsize=30x20):
import pylab as plt
fig,(ax0,ax1) = plt.subplots(nrows=1,ncols=2, figsize=(30,20))
data_df.plot(ax=ax0)
model_df.plot(ax=ax1)
You can use matplotlib.pyplot.subplots :
import numpy as np
import pandas as pd
import matplotlib.pyplot as plt
data_df = pd.DataFrame(np.random.randint(0,100,size=(15, 2)), columns=list('AB'))
model_df = pd.DataFrame(np.random.randint(0,100,size=(15, 2)), columns=list('AB'))
fig, axes = plt.subplots(nrows=1, ncols=2, figsize=(12,4))
for col, ax in zip(data_df, axes):
data_df[col].plot(ax=ax, label=f"data_df ({col})")
model_df[col].plot(ax=ax, label=f"model_df ({col})")
ax.legend()
# Output :

xarray.plot.contour not printing contour labels

I am trying something like this:
import xarray as xr
import numpy as np
(lon,lat)=np.meshgrid(np.arange(0,6,1),np.arange(0,6,1))
da_data=xr.DataArray(data=np.random.randn(6,6),dims=['y','x'],
coords=dict(LAT=(['y','x'],lat), LON=(['y','x'],lon)) )
da_data.plot.contour(kwargs=dict(inline=True))
I can see the contours but no labels. What am I doing wrong?
xarray.plot uses matplotlib as a backend, and you can replace your last line with the following, using matplotlib's Axis.clabel
fig, ax = plt.subplots()
CS = da_data.plot.contour(kwargs=dict(inline=True), ax=ax)
ax.clabel(CS)
See the matplotlib.contour.ContourLabeler.clabel documentation and the countour label demo for more info.

Is there a function in plotly that is equivalent to plt.axes('scaled') in matplotlib for the aspect ratio of a graph?

I want to plot some coordinates using Plotly express because it allows me a more interactive approach, but I can not find the way to control the scale in the axis in the way I can manage with matplotlib.pyplot in one single line
plt.axis("scaled")
Could you please share some suggestions? Thanks.
Here is the code using Plotly express:
fig = px.scatter(coordinates_utm, x='EASTING', y='NORTHING', title=name,
hover_name=coordinates_utm.index,
hover_data={'NORTHING':':.6f','EASTING': ':.6f'})
fig.add_trace(px.scatter(coordinates_utm_lineal, x='x', y='ylineal',color_discrete_sequence=['red']).data[0])
Here is the code using plt:
fig.show()
plt.figure()
plt.scatter(coordinates_utm_lineal.x,coordinates_utm_lineal.ylineal,s=2)
plt.scatter(coordinates_utm.EASTING,coordinates_utm.NORTHING, s=2)
plt.axis("scaled")
plt.show()
This is my current output
Sadly, you didn't provide a fully reproducible example, so I'm going to create my own.
Also, I'm not really familiar with plt.axis("scaled"), as I usually use plt.axis("equal"). Reading the documentation associated to plt.axis, they appear to be somewhat similar. See if the following answer can satisfy your needs.
import plotly.express as px
import numpy as np
t = np.linspace(0, 2*np.pi)
x = np.cos(t)
y = np.sin(t)
fig = px.scatter(x=x, y=y)
fig.layout.yaxis.scaleanchor="x"
fig.show()

Creating a grouped bar plot with Seaborn

I am trying to create a grouped bar graph using Seaborn but I am getting a bit lost in the weeds. I actually have it working but it does not feel like an elegant solution. Seaborn only seems to support clustered bar graphs when there is a binary option such as Male/Female. (https://seaborn.pydata.org/examples/grouped_barplot.html)
It does not feel right having to fall back onto matplotlib so much - using the subplots feels a bit dirty :). Is there a way of handling this completely in Seaborn?
Thanks,
Andrew
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
from matplotlib import rcParams
sns.set_theme(style="whitegrid")
rcParams.update({'figure.autolayout': True})
dataframe = pd.read_csv("https://raw.githubusercontent.com/mooperd/uk-towns/master/uk-towns-sample.csv")
dataframe = dataframe.groupby(['nuts_region']).agg({'elevation': ['mean', 'max', 'min'],
'nuts_region': 'size'}).reset_index()
dataframe.columns = list(map('_'.join, dataframe.columns.values))
# We need to melt our dataframe down into a long format.
tidy = dataframe.melt(id_vars='nuts_region_').rename(columns=str.title)
# Create a subplot. A Subplot makes it convenient to create common layouts of subplots.
# https://matplotlib.org/3.3.3/api/_as_gen/matplotlib.pyplot.subplots.html
fig, ax1 = plt.subplots(figsize=(6, 6))
# https://stackoverflow.com/questions/40877135/plotting-two-columns-of-dataframe-in-seaborn
g = sns.barplot(x='Nuts_Region_', y='Value', hue='Variable', data=tidy, ax=ax1)
plt.tight_layout()
plt.xticks(rotation=45, ha="right")
plt.show()
I'm not sure why you need seaborn. Your data is wide format, so pandas does it pretty well without the need for melting:
from matplotlib import rcParams
sns.set(style="whitegrid")
rcParams.update({'figure.autolayout': True})
fig, ax1 = plt.subplots(figsize=(12,6))
dataframe.plot.bar(x='nuts_region_', ax=ax1)
plt.tight_layout()
plt.xticks(rotation=45, ha="right")
plt.show()
Output:

how to prevent seaborn to skip year in xtick label in Timeseries Plot

I have included the screenshot of the plot. Is there a way to prevent seaborn from skipping the xtick labels in timeseries data.
Most seaborn functions return a matplotlib object, so you can control the number of major ticks displayed via matplotlib. By default, matplotlib will auto-scale, which is why it hides some year labels, you can try to set the MaxNLocator.
Consider the following example:
import pandas as pd
import seaborn as sns
import matplotlib.pyplot as plt
# load data
df = sns.load_dataset('flights')
df.drop_duplicates('year', inplace=True)
df.year = df.year.astype('str')
# plot
fig, ax = plt.subplots(figsize=(5, 2))
sns.lineplot(x='year', y='passengers', data=df, ax=ax)
ax.xaxis.set_major_locator(plt.MaxNLocator(5))
This gives you:
ax.xaxis.set_major_locator(plt.MaxNLocator(10))
will give you
Agree with answer of #steven, just want to say that methods for xticks like plt.xticks or ax.xaxis.set_ticks seem more natural to me. Full details can be found here.