Aspose于2002年3月在澳大利亞悉尼創(chuàng)建,旗下產(chǎn)品覆蓋文檔、圖表、PDF、條碼、OCR、CAD、HTML、電子郵件等各個文檔管理領(lǐng)域,為全球.NET 、Java、C ++等10余種平臺開發(fā)人員提供豐富的開發(fā)選擇。
此鏈接「鏈接」是官方的Aspose.PDF for Java文檔,包含了非常全的Java API使用示例,可以作為操作PDF的一手資料。
Aspose.PDF for Java
public static void processImages(String filePath) {
Document document=new Document(filePath);
for (int i=1; i <=document.getPages().size(); i++) {
Page page=document.getPages().get_Item(i);
for (int j=1; j <=page.getResources().getImages().size(); j++) {
XImage image=page.getResources().getImages().get_Item(j);
System.out.println(image);
// delete by image features
if (image.getWidth()==302 && image.getHeight()==95) {
System.out.println("delete ad image");
image.delete();
}
}
}
document.save(filePath.replace(".pdf", System.currentTimeMillis() + ".pdf"));
}
代碼解析:
較七個在 Python 中繪圖的庫和 API,看看哪個最能滿足你的需求。
(本文字數(shù):8312,閱讀時長大約:9 分鐘)
比較七個在 Python 中繪圖的庫和 API,看看哪個最能滿足你的需求。
“如何在 Python 中繪圖?”曾經(jīng)這個問題有一個簡單的答案:Matplotlib 是唯一的辦法。如今,Python 作為數(shù)據(jù)科學(xué)的語言,有著更多的選擇。你應(yīng)該用什么呢?
本指南將幫助你決定。
它將向你展示如何使用四個最流行的 Python 繪圖庫:Matplotlib、Seaborn、Plotly 和 Bokeh,再加上兩個值得考慮的優(yōu)秀的后起之秀:Altair,擁有豐富的 API;Pygal,擁有漂亮的 SVG 輸出。我還會看看 Pandas 提供的非常方便的繪圖 API。
對于每一個庫,我都包含了源代碼片段,以及一個使用 Anvil 的完整的基于 Web 的例子。Anvil 是我們的平臺,除了 Python 之外,什么都不用做就可以構(gòu)建網(wǎng)絡(luò)應(yīng)用。讓我們一起來看看。
每個庫都采取了稍微不同的方法來繪制數(shù)據(jù)。為了比較它們,我將用每個庫繪制同樣的圖,并給你展示源代碼。對于示例數(shù)據(jù),我選擇了這張 1966 年以來英國大選結(jié)果的分組柱狀圖。
Bar chart of British election data
我從維基百科上整理了 英國選舉史的數(shù)據(jù)集 :從 1966 年到 2019 年,保守黨、工黨和自由黨(廣義)在每次選舉中贏得的英國議會席位數(shù),加上“其他”贏得的席位數(shù)。你可以 以 CSV 文件格式下載它 。
Matplotlib 是最古老的 Python 繪圖庫,現(xiàn)在仍然是最流行的。它創(chuàng)建于 2003 年,是 SciPy Stack 的一部分,SciPy Stack 是一個類似于 Matlab 的開源科學(xué)計算庫。
Matplotlib 為你提供了對繪制的精確控制。例如,你可以在你的條形圖中定義每個條形圖的單獨的 X 位置。下面是繪制這個圖表的代碼(你可以在 這里 運行):
import matplotlib.pyplot as plt
import numpy as np
from votes import wide as df
# Initialise a figure. subplots() with no args gives one plot.
fig, ax=plt.subplots()
# A little data preparation
years=df['year']
x=np.arange(len(years))
# Plot each bar plot. Note: manually calculating the 'dodges' of the bars
ax.bar(x - 3*width/2, df['conservative'], width, label='Conservative', color='#0343df')
ax.bar(x - width/2, df['labour'], width, label='Labour', color='#e50000')
ax.bar(x + width/2, df['liberal'], width, label='Liberal', color='#ffff14')
ax.bar(x + 3*width/2, df['others'], width, label='Others', color='#929591')
# Customise some display properties
ax.set_ylabel('Seats')
ax.set_title('UK election results')
ax.set_xticks(x) # This ensures we have one tick per year, otherwise we get fewer
ax.set_xticklabels(years.astype(str).values, rotation='vertical')
ax.legend()
# Ask Matplotlib to show the plot
plt.show()
這是用 Matplotlib 繪制的選舉結(jié)果:
Matplotlib plot of British election data
Seaborn 是 Matplotlib 之上的一個抽象層;它提供了一個非常整潔的界面,讓你可以非常容易地制作出各種類型的有用繪圖。
不過,它并沒有在能力上有所妥協(xié)!Seaborn 提供了訪問底層 Matplotlib 對象的 逃生艙口 ,所以你仍然可以進行完全控制。
Seaborn 的代碼比原始的 Matplotlib 更簡單(可在 此處 運行):
import seaborn as sns
from votes import long as df
# Some boilerplate to initialise things
sns.set()
plt.figure()
# This is where the actual plot gets made
ax=sns.barplot(data=df, x="year", y="seats", hue="party", palette=['blue', 'red', 'yellow', 'grey'], saturation=0.6)
# Customise some display properties
ax.set_title('UK election results')
ax.grid(color='#cccccc')
ax.set_ylabel('Seats')
ax.set_xlabel(None)
ax.set_xticklabels(df["year"].unique().astype(str), rotation='vertical')
# Ask Matplotlib to show it
plt.show()
并生成這樣的圖表:
Seaborn plot of British election data
Plotly 是一個繪圖生態(tài)系統(tǒng),它包括一個 Python 繪圖庫。它有三個不同的接口:
Plotly 繪圖被設(shè)計成嵌入到 Web 應(yīng)用程序中。Plotly 的核心其實是一個 JavaScript 庫!它使用 D3 和 stack.gl 來繪制圖表。
你可以通過向該 JavaScript 庫傳遞 JSON 來構(gòu)建其他語言的 Plotly 庫。官方的 Python 和 R 庫就是這樣做的。在 Anvil,我們將 Python Plotly API 移植到了 Web 瀏覽器中運行 。
這是使用 Plotly 的源代碼(你可以在這里 運行 ):
import plotly.graph_objects as go
from votes import wide as df
# Get a convenient list of x-values
years=df['year']
x=list(range(len(years)))
# Specify the plots
bar_plots=[
go.Bar(x=x, y=df['conservative'], name='Conservative', marker=go.bar.Marker(color='#0343df')),
go.Bar(x=x, y=df['labour'], name='Labour', marker=go.bar.Marker(color='#e50000')),
go.Bar(x=x, y=df['liberal'], name='Liberal', marker=go.bar.Marker(color='#ffff14')),
go.Bar(x=x, y=df['others'], name='Others', marker=go.bar.Marker(color='#929591')),
]
# Customise some display properties
layout=go.Layout(
title=go.layout.Title(text="Election results", x=0.5),
yaxis_title="Seats",
xaxis_tickmode="array",
xaxis_tickvals=list(range(27)),
xaxis_ticktext=tuple(df['year'].values),
)
# Make the multi-bar plot
fig=go.Figure(data=bar_plots, layout=layout)
# Tell Plotly to render it
fig.show()
選舉結(jié)果圖表:
Plotly plot of British election data
Bokeh (發(fā)音為 “BOE-kay”)擅長構(gòu)建交互式繪圖,所以這個標準的例子并沒有將其展現(xiàn)其最好的一面。和 Plotly 一樣,Bokeh 的繪圖也是為了嵌入到 Web 應(yīng)用中,它以 HTML 文件的形式輸出繪圖。
下面是使用 Bokeh 的代碼(你可以在 這里 運行):
from bokeh.io import show, output_file
from bokeh.models import ColumnDataSource, FactorRange, HoverTool
from bokeh.plotting import figure
from bokeh.transform import factor_cmap
from votes import long as df
# Specify a file to write the plot to
output_file("elections.html")
# Tuples of groups (year, party)
x=[(str(r[1]['year']), r[1]['party']) for r in df.iterrows()]
y=df['seats']
# Bokeh wraps your data in its own objects to support interactivity
source=ColumnDataSource(data=dict(x=x, y=y))
# Create a colourmap
cmap={
'Conservative': '#0343df',
'Labour': '#e50000',
'Liberal': '#ffff14',
'Others': '#929591',
}
fill_color=factor_cmap('x', palette=list(cmap.values()), factors=list(cmap.keys()), start=1, end=2)
# Make the plot
p=figure(x_range=FactorRange(*x), width=1200, title="Election results")
p.vbar(x='x', top='y', width=0.9, source=source, fill_color=fill_color, line_color=fill_color)
# Customise some display properties
p.y_range.start=0
p.x_range.range_padding=0.1
p.yaxis.axis_label='Seats'
p.xaxis.major_label_orientation=1
p.xgrid.grid_line_color=None
圖表如下:
Bokeh plot of British election data
Altair 是基于一種名為 Vega 的聲明式繪圖語言(或“可視化語法”)。這意味著它具有經(jīng)過深思熟慮的 API,可以很好地擴展復(fù)雜的繪圖,使你不至于在嵌套循環(huán)的地獄中迷失方向。
與 Bokeh 一樣,Altair 將其圖形輸出為 HTML 文件。這是代碼(你可以在 這里 運行):
import altair as alt
from votes import long as df
# Set up the colourmap
cmap={
'Conservative': '#0343df',
'Labour': '#e50000',
'Liberal': '#ffff14',
'Others': '#929591',
}
# Cast years to strings
df['year']=df['year'].astype(str)
# Here's where we make the plot
chart=alt.Chart(df).mark_bar().encode(
x=alt.X('party', title=None),
y='seats',
column=alt.Column('year', sort=list(df['year']), title=None),
color=alt.Color('party', scale=alt.Scale(domain=list(cmap.keys()), range=list(cmap.values())))
)
# Save it as an HTML file.
chart.save('altair-elections.html')
結(jié)果圖表:
Altair plot of British election data
Pygal 專注于視覺外觀。它默認生成 SVG 圖,所以你可以無限放大它們或打印出來,而不會被像素化。Pygal 繪圖還內(nèi)置了一些很好的交互性功能,如果你想在 Web 應(yīng)用中嵌入繪圖,Pygal 是另一個被低估了的候選者。
代碼是這樣的(你可以在 這里 運行它):
import pygal
from pygal.style import Style
from votes import wide as df
# Define the style
custom_style=Style(
colors=('#0343df', '#e50000', '#ffff14', '#929591')
font_family='Roboto,Helvetica,Arial,sans-serif',
background='transparent',
label_font_size=14,
)
# Set up the bar plot, ready for data
c=pygal.Bar(
title="UK Election Results",
style=custom_style,
y_title='Seats',
width=1200,
x_label_rotation=270,
)
# Add four data sets to the bar plot
c.add('Conservative', df['conservative'])
c.add('Labour', df['labour'])
c.add('Liberal', df['liberal'])
c.add('Others', df['others'])
# Define the X-labels
c.x_labels=df['year']
# Write this to an SVG file
c.render_to_file('pygal.svg')
繪制結(jié)果:
Pygal plot of British election data
Pandas 是 Python 的一個極其流行的數(shù)據(jù)科學(xué)庫。它允許你做各種可擴展的數(shù)據(jù)處理,但它也有一個方便的繪圖 API。因為它直接在數(shù)據(jù)幀上操作,所以 Pandas 的例子是本文中最簡潔的代碼片段,甚至比 Seaborn 的代碼還要短!
Pandas API 是 Matplotlib 的一個封裝器,所以你也可以使用底層的 Matplotlib API 來對你的繪圖進行精細的控制。
這是 Pandas 中的選舉結(jié)果圖表。代碼精美簡潔!
from matplotlib.colors import ListedColormap
from votes import wide as df
cmap=ListedColormap(['#0343df', '#e50000', '#ffff14', '#929591'])
ax=df.plot.bar(x='year', colormap=cmap)
ax.set_xlabel(None)
ax.set_ylabel('Seats')
ax.set_title('UK election results')
plt.show()
繪圖結(jié)果:
Pandas plot of British election data
要運行這個例子,請看 這里 。
Python 提供了許多繪制數(shù)據(jù)的方法,無需太多的代碼。雖然你可以通過這些方法快速開始創(chuàng)建你的繪圖,但它們確實需要一些本地配置。如果需要, Anvil 為 Python 開發(fā)提供了精美的 Web 體驗。祝你繪制愉快!
via: https://opensource.com/article/20/4/plot-data-python
作者: Shaun Taylor-Morgan 譯者: wxy 校對: wxy
本文由 LCTT 原創(chuàng)編譯, Linux中國 榮譽推出
譯自: https://opensource.com/article/18/9/open-source-javascript-chart-libraries
作者: Dr.michael J.garbade
譯者: 周家未
圖表及其它可視化方式讓傳遞數(shù)據(jù)的信息變得更簡單。
對于數(shù)據(jù)可視化和制作精美網(wǎng)站來說,圖表和圖形很重要。視覺上的展示讓分析大塊數(shù)據(jù)及傳遞信息變得更簡單。JavaScript 圖表庫能讓數(shù)據(jù)以極好的、易于理解的和交互的方式進行可視化,還能夠優(yōu)化你的網(wǎng)站設(shè)計。
本文會帶你學(xué)習最好的 3 個開源 JavaScript 圖表庫。
Chart.js 是一個開源的 JavaScript 庫,你可以在自己的應(yīng)用中用它創(chuàng)建生動美麗和交互式的圖表。使用它需要遵循 MIT 協(xié)議。
使用 Chart.js,你可以創(chuàng)建各種各樣令人印象深刻的圖表和圖形,包括條形圖、折線圖、范圍圖、線性標度和散點圖。它可以響應(yīng)各種設(shè)備,使用 HTML5 Canvas 元素進行繪制。
示例代碼如下,它使用該庫繪制了一個條形圖。本例中我們使用 Chart.js 的內(nèi)容分發(fā)網(wǎng)絡(luò)(CDN)來包含這個庫。注意這里使用的數(shù)據(jù)僅用于展示。
<!DOCTYPE html>
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/Chart.js/2.5.0/Chart.min.js"></script>
</head>
<body>
<canvas id="bar-chart" width=300" height="150"></canvas>
<script>
new Chart(document.getElementById("bar-chart"), {
type: 'bar',
data: {
labels: ["North America", "Latin America", "Europe", "Asia", "Africa"],
datasets: [
{
label: "Number of developers (millions)",
backgroundColor: ["red", "blue","yellow","green","pink"],
data: [7,4,6,9,3]
}
]
},
options: {
legend: { display: false },
title: {
display: true,
text: 'Number of Developers in Every Continent'
},
scales: {
yAxes: [{
ticks: {
beginAtZero:true
}
}]
}
}
});
</script>
</body>
</html>
如你所見,通過設(shè)置 type 和 bar 來構(gòu)造條形圖。你可以把條形體的方向改成其他類型 —— 比如把 type 設(shè)置成 horizontalBar。
在 backgroundColor 數(shù)組參數(shù)中提供顏色類型,就可以設(shè)置條形圖的顏色。
顏色被分配給關(guān)聯(lián)數(shù)組中相同索引的標簽和數(shù)據(jù)。例如,第二個標簽 “Latin American”,顏色會是 “藍色(blue)”(第二個顏色),數(shù)值是 4(data 中的第二個數(shù)字)。
代碼的執(zhí)行結(jié)果如下。
Chartist.js 是一個簡單的 JavaScript 動畫庫,你能夠自制美麗的響應(yīng)式圖表,或者進行其他創(chuàng)作。使用它需要遵循 WTFPL 或者 MIT 協(xié)議。
這個庫是由一些對現(xiàn)有圖表工具不滿的開發(fā)者進行開發(fā)的,它可以為設(shè)計師或程序員提供美妙的功能。
在項目中包含 Chartist.js 庫后,你可以使用它們來創(chuàng)建各式各樣的圖表,包括動畫,條形圖和折線圖。它使用 SVG 來動態(tài)渲染圖表。
這里是使用該庫繪制一個餅圖的例子。
<!DOCTYPE html>
<html>
<head>
<link href="https//cdn.jsdelivr.net/chartist.js/latest/chartist.min.css" rel="stylesheet" type="text/css" />
<style>
.ct-series-a .ct-slice-pie {
fill: hsl(100, 20%, 50%); /* filling pie slices */
stroke: white; /*giving pie slices outline */
stroke-width: 5px; /* outline width */
}
.ct-series-b .ct-slice-pie {
fill: hsl(10, 40%, 60%);
stroke: white;
stroke-width: 5px;
}
.ct-series-c .ct-slice-pie {
fill: hsl(120, 30%, 80%);
stroke: white;
stroke-width: 5px;
}
.ct-series-d .ct-slice-pie {
fill: hsl(90, 70%, 30%);
stroke: white;
stroke-width: 5px;
}
.ct-series-e .ct-slice-pie {
fill: hsl(60, 140%, 20%);
stroke: white;
stroke-width: 5px;
}
</style>
</head>
<body>
<div class="ct-chart ct-golden-section"></div>
<script src="https://cdn.jsdelivr.net/chartist.js/latest/chartist.min.js"></script>
<script>
var data={
series: [45, 35, 20]
};
var sum=function(a, b) { return a + b };
new Chartist.Pie('.ct-chart', data, {
labelInterpolationFnc: function(value) {
return Math.round(value / data.series.reduce(sum) * 100) + '%';
}
});
</script>
</body>
</html>
使用 Chartist JavaScript 庫,你可以使用各種預(yù)先構(gòu)建好的 CSS 樣式,而不是在項目中指定各種與樣式相關(guān)的部分。你可以使用這些樣式來設(shè)置已創(chuàng)建的圖表的外觀。
比如,預(yù)創(chuàng)建的 CSS 類 .ct-chart 是用來構(gòu)建餅狀圖的容器。還有 .ct-golden-section 類可用于獲取縱橫比,它基于響應(yīng)式設(shè)計進行縮放,幫你解決了計算固定尺寸的麻煩。Chartist 還提供了其它類別的比例容器,你可以在自己的項目中使用它們。
為了給各個扇形設(shè)置樣式,可以使用默認的 .ct-serials-a 類。字母 a 是根據(jù)系列的數(shù)量變化的(a、b、c,等等),因此它與每個要設(shè)置樣式的扇形相對應(yīng)。
Chartist.Pie 方法用來創(chuàng)建一個餅狀圖。要創(chuàng)建另一種類型的圖表,比如折線圖,請使用 Chartist.Line。
代碼的執(zhí)行結(jié)果如下。
D3.js 是另一個好用的開源 JavaScript 圖表庫。使用它需要遵循 BSD 許可證。D3 的主要用途是,根據(jù)提供的數(shù)據(jù),處理和添加文檔的交互功能,。
借助這個 3D 動畫庫,你可以通過 HTML5、SVG 和 CSS 來可視化你的數(shù)據(jù),并且讓你的網(wǎng)站變得更精美。更重要的是,使用 D3,你可以把數(shù)據(jù)綁定到文檔對象模型(DOM)上,然后使用基于數(shù)據(jù)的函數(shù)改變文檔。
示例代碼如下,它使用該庫繪制了一個簡單的條形圖。
<!DOCTYPE html>
<html>
<head>
<style>
.chart div {
font: 15px sans-serif;
background-color: lightblue;
text-align: right;
padding:5px;
margin:5px;
color: white;
font-weight: bold;
}
</style>
</head>
<body>
<div class="chart"></div>
<script src="https://cdnjs.cloudflare.com/ajax/libs/d3/5.5.0/d3.min.js"></script>
<script>
var data=[342,222,169,259,173];
d3.select(".chart")
.selectAll("div")
.data(data)
.enter()
.append("div")
.style("width", function(d){ return d + "px"; })
.text(function(d) { return d; });
</script>
</body>
</html>
使用 D3 庫的主要概念是應(yīng)用 CSS 樣式選擇器來定位 DOM 節(jié)點,然后對其執(zhí)行操作,就像其它的 DOM 框架,比如 JQuery。
將數(shù)據(jù)綁定到文檔上后,.enter() 函數(shù)會被調(diào)用,為即將到來的數(shù)據(jù)構(gòu)建新的節(jié)點。所有在 .enter() 之后調(diào)用的方法會為數(shù)據(jù)中的每一個項目調(diào)用一次。
代碼的執(zhí)行結(jié)果如下。
JavaScript 圖表庫提供了強大的工具,你可以將自己的網(wǎng)絡(luò)資源進行數(shù)據(jù)可視化。通過這三個開源庫,你可以把自己的網(wǎng)站變得更好看,更容易使用。
你知道其它強大的用于創(chuàng)造 JavaScript 動畫效果的前端庫嗎?請在下方的評論區(qū)留言分享。
via: https://opensource.com/article/18/9/open-source-javascript-chart-libraries
作者: Dr.Michael J.Garbade 選題: lujun9972 譯者: BriFuture 校對: wxy
本文由 LCTT 原創(chuàng)編譯, Linux中國 榮譽推出
*請認真填寫需求信息,我們會在24小時內(nèi)與您取得聯(lián)系。