code is as below
import pandas as pd
import matplotlib.pyplot as plt
dates = ['2010-11', '2011-12', '2012-13', '2013-14', '2014-15', '2015-16', '2016-17']
steps = [9000, 9500.756, 9800.859, 10000.262, 9800.972, 10500.058, 11300.703]
fig=plt.figure(figsize=(10,8))
ax=fig.add_subplot(111)
ax.set(xlabel="X-axis",ylabel="Y-axis",title="2d line plot",xlim=(0,8),ylim=(2000,15000))
ax.plot(dates,steps, color='red',linewidth=2,marker='o',label='LPG')
plt.show()
plt.close('all')
Running this code I am getting a plot as below
Here the plot is starting from y-axis how to push it little right
In your command
ax.set(xlabel="X-axis",ylabel="Y-axis",title="2d line plot",xlim=(0,8),ylim=(2000,15000))
change the first number in parameter xlim=(0,8) to some negative value; use e.g. xlim=(-.5,8):
ax.set(xlabel="X-axis",ylabel="Y-axis",title="2d line plot",xlim=(-.5,8),ylim=(2000,15000))
Related
I try to plot a bar graph with a pre-defined number of grid lines like below. However, once I plot it, some yticklabels (A_2,A_3,etc) have not shown (only A_1, A_5, A_9,A_13,A_17 shown). I want to keep all ytick labels, but the gridline should be the same as x axis. Do you have any ideas to fix it?
import matplotlib.pyplot as plt
import numpy as np
mdict={"Column1":["A_"+str(i) for i in range(1,21)],"Value":[i for i in range(1,21)]}
# Create a dataframe
df=pd.DataFrame(mdict)
# Set plot params
fig, ax = plt.subplots(figsize=(12,8))
ax.barh(df.Column1,df.Value, color="darkgray",edgecolor="black", linewidth=0.5)
ax.set_xlabel("Numbers", fontsize=15)
# ax.set_yticklabels(list(df_cor.Country.values.tolist()), fontsize=15)
major_ticks_top=np.linspace(0,20,6)
minor_ticks_top=np.linspace(0,20,6)
ax.set_xticks(major_ticks_top)
ax.set_yticks(minor_ticks_top)
ax.grid(alpha=0.2,color="black")
plt.show()
I wouldn't explicitly set the ticks and labels but modify the output matplotlib generates:
import matplotlib.pyplot as plt
import pandas as pd
from matplotlib.ticker import MultipleLocator
mdict={"Column1":["A_"+str(i) for i in range(1,21)],"Value":[i for i in range(1,21)]}
df=pd.DataFrame(mdict)
fig, ax = plt.subplots(figsize=(12,8))
ax.barh(df.Column1, df.Value, color="darkgray", edgecolor="black", linewidth=0.5)
ax.set_xlabel("Numbers", fontsize=15)
#set every fourth tick
n=4
ax.xaxis.set_major_locator(MultipleLocator(n))
ax.grid(alpha=0.2,color="black")
#remove unwanted gridlines on the y-axis
ygrd_lines = ax.get_ygridlines()
[grd_line.set_visible(False) for i, grd_line in enumerate(ygrd_lines) if i%n]
plt.show()
Sample output:
Methods used:
MultipleLocator() setting ticks at defined intervals
.get_ygridlines returning gridlines as a list of Line2D objects for further modification
I'm fairly new to plotting contour lines. When plotting ice data that crosses over longitude zero in the Arctic, the contour lines create horizontal lines that span the x axis. Ideally I'd merge the lines so they created one solid contour, but failing that just removing the horizontal lines would be enough.
https://imgur.com/VU1IlNA (I'm new and not allowed to post pictures yet, but this shows the problem clearly)
from netCDF4 import Dataset, MFDataset, num2date
import numpy as np
import cartopy.crs as ccrs
from cartopy.util import add_cyclic_point
import pandas as pd
from netCDF4 import Dataset as NetCDFFile
import matplotlib.pyplot as plt
nc = NetCDFFile('LongitudeLatitudeGrid-n3125-Svalbard- from20190129.hdf')
lats = nc.variables['Latitudes'][:]
lons = nc.variables['Longitudes'][:]
nc17 = NetCDFFile('asi-AMSR2-n3125-20190517-v5.4.hdf')
ice17 = nc17.variables['ASI Ice Concentration'][:]
fig = plt.figure(figsize=(30,20))
ax6 = plt.subplot(2,3,6,projection=ccrs.Mercator(min_latitude=77,max_latitude=81))
mm = ax6.contour(lons,lats,ice17,vmin=0,vmax=100,
transform=ccrs.PlateCarree(),cmap='BuPu',zorder=1)
plt.title('May 17th stations: δ15N vaules',size='x-large')
ax6.set_extent([-10,10,77,81])
ax6.coastlines()
Expected results are a clean contour line, with no gap, but instead a gap appears as shown.
I managed to fix this, the issue was that my longitudinal values jumped from 0 to 360 at longitude zero. By subtracting 360 from all longitude values > 180 the problem was solved, and the plot looks appropriate now.
I would like to plot a figure with double x axis, and format the ticklabel in the upper axis to scientific notations.
import numpy as np
import matplotlib.pyplot as plt
imp1=np.arange(0,2,2/50)
imp1_pdf=np.arange(0,6,6/50)
fig1=plt.figure()
axs1=fig1.add_subplot(111)
axs1.set_xlim(0,2)
axs1.set_ylim(0,6.5)
axs2 = axs1.twiny()
axs1.plot(imp1,imp1_pdf)
new_tick_locations=axs1.get_xticks()
axs2.set_xticks(new_tick_locations)
axs2.set_xticklabels(new_tick_locations/1000)
axs2.axes.ticklabel_format(axis='x',style='sci',scilimits=(0,0))
axs1.grid(b=True, which='major',linestyle='-')
fig1.tight_layout()
fig1.savefig('tickformat.png',dpi=600)
Without the ticklabel formatting, the figure looks like this:
But when I try to format the upper x axis, there is an error like this:
AttributeError: This method only works with the ScalarFormatter.
If I use an alternative method, which is to use the FormatStrFormatter
from matplotlib.ticker import FormatStrFormatter
axs2.xaxis.set_major_formatter(FormatStrFormatter('%.1e'))
The upper x axis value will become the same with the lower x axis value like this:
Could someone tell me how to solve this problem please?
The problem is you are trying to modify the custom labels which are just strings you defined (new_tick_locations/1000). The real values on the twin axis are the same as that on the lower axis. You are just modifying the tick labels. One way to get things done is to construct modified tick labels in Scientific Format using Decimal and then assign them to the upper x-axis. You can then choose any factor instead of 1000, which you want to display
import numpy as np
from decimal import Decimal
import matplotlib.pyplot as plt
imp1=np.arange(0,2,2/50)
imp1_pdf=np.arange(0,6,6/50)
fig1=plt.figure()
axs1=fig1.add_subplot(111)
axs1.set_xlim(0,2)
axs1.set_ylim(0,6.5)
axs2 = axs1.twiny()
axs1.plot(imp1,imp1_pdf)
new_tick_locations=axs1.get_xticks()
ticks = ['%.2E' % Decimal(i) for i in (new_tick_locations/1000)] # <-- make new ticks
axs2.set_xticks(new_tick_locations)
axs2.set_xticklabels(ticks, rotation = 45) # <-- assign new ticks and rotate them
axs1.grid(b=True, which='major',linestyle='-')
fig1.tight_layout()
I have an multi-dimensional array of 147637 rows and 175 columns. Now I want to plot only one of the column , i.e, the last column. The last column is filled with 0s in all rows except these 5 rows: 29528, 59051, 88583, 118110, 147636. These rows have a value of 1.
Below is the code that I used to plot:
import matplotlib.pyplot as plt
workBoundary=-1
fig,(ax1)=plt.subplots(nrows=1,ncols=1)
ax1.plot(allPathsDistance[:,workBoundary],color='maroon')
plt.show()
Below is the output:
Notice the x axis. According to this figure there is no '1' value between rows 0 and 60000.
But when I zoom in to the picture:
A '1' valued data point appears at roughly 30000th row as it should.(29528th row, to be exact). I can't figure out why this is happening. Can anyone help rectify this ? I restarted the Spyder IDE but this behavior did not change.
Additional Info:
if the x axis limits are edited to not show 0 as follows:
import matplotlib.pyplot as plt
workBoundary=-1
fig,(ax1)=plt.subplots(nrows=1,ncols=1)
ax1.plot(allPathsDistance[:,workBoundary],color='maroon')
ax1.set_xlim(left=10)
plt.show()
then the line at 30000th row appears. result:
This seems to suggest that the matplotlib is not plotting the data at some of the positions on the plot area.
Version info:
matplotlib: 2.1.0
Spyder: 3.1.4
Windows:7
Python: 3.6.3
If you really have just very sharp spikes that are sparsely distributed in your data, you can use ax.vlines() to make sure they are all visible:
from matplotlib import pyplot as plt
import numpy as np
##setting up the data
allPathsDistance = np.zeros(147637)
allPathsDistance[[29528, 59051, 88583, 118110, 147636]] = 1.0
xvals = np.arange(allPathsDistance.shape[0])
##masking:
mask = allPathsDistance>0
##plotting
fig, ax = plt.subplots()
ax.vlines(xvals[mask], np.zeros_like(xvals[mask]),allPathsDistance[mask])
ax.set_xlim([xvals[0]-1000,xvals[-1]+1000])
plt.show()
...and here is the result:
Hope this helps.
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3,3,1000)
t = np.ones(1000)
f = x**2
plt.scatter(x,f) #plot1
plt.scatter(t,f) #plot2
plt.show()
I'd like to draw pile datas up.
when you look at upper exmaple, you can see two plot.plot1 is y=x^2 and plot2 is a line of perpendicular with x-axis. datas of plot2 are showing just a line all of datas. it means, i guess there is a section of more dense near the minimum point of plot1 (0,0).
but when you look at plot2 , it just show a line because of no density.
how can i fix this code?
Try axvline if you want a line that is perpendicular to the x-axis:
import numpy as np
import matplotlib.pyplot as plt
x = np.linspace(-3,3,1000)
f = x**2
plt.scatter(x,f) #plot1
plt.axvline(1) #plot2
plt.show()